import React, { useState, useEffect } from 'react';
import { Plus, Trash2, ListTree, RefreshCw, Image as ImageIcon } from 'lucide-react';
import { SiteSettings } from '../types';

export interface CategoryData {
  name: string;
  icon?: string;
}

interface CategoryManagerProps {
  settings: SiteSettings;
  onSave: (updates: Partial<SiteSettings>) => Promise<void>;
  onUploadImage?: (file: File) => Promise<string | null>;
}

const CategoryManager: React.FC<CategoryManagerProps> = ({ settings, onSave, onUploadImage }) => {
  const [categories, setCategories] = useState<CategoryData[]>([]);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [newCategoryIcon, setNewCategoryIcon] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    if (settings.categoriesJson) {
      try {
        const parsed = JSON.parse(settings.categoriesJson);
        const mapped = parsed.map((c: any) => typeof c === 'string' ? { name: c, icon: '' } : c);
        setCategories(mapped);
      } catch (e) {
        console.error('Failed to parse categoriesJson', e);
        setCategories([]);
      }
    } else {
      setCategories([{name: 'Basic', icon: ''}, {name: 'Premium', icon: ''}]); // default fallback
    }
  }, [settings.categoriesJson]);

  const handleSaveCategories = async (updatedCategories: CategoryData[]) => {
    setIsSaving(true);
    try {
      await onSave({ categoriesJson: JSON.stringify(updatedCategories) });
    } finally {
      setIsSaving(false);
    }
  };

  const handleAddCategory = () => {
    if (!newCategoryName.trim()) return;
    if (categories.some(c => c.name === newCategoryName.trim())) {
      alert("Category already exists!");
      return;
    }
    
    const updated = [...categories, { name: newCategoryName.trim(), icon: newCategoryIcon }];
    setCategories(updated);
    setNewCategoryName('');
    setNewCategoryIcon('');
    handleSaveCategories(updated);
  };

  const handleDeleteCategory = (catToDelete: string) => {
    if (!window.confirm(`Are you sure you want to delete "${catToDelete}"? Product associations will remain but it won't appear in filters.`)) {
      return;
    }
    const updated = categories.filter(c => c.name !== catToDelete);
    setCategories(updated);
    handleSaveCategories(updated);
  };

  const handleIconUpload = async (e: React.ChangeEvent<HTMLInputElement>, index: number, isNew = false) => {
    if(!onUploadImage) {
        alert("Image upload is not configured.");
        return;
    }
    const file = e.target.files?.[0];
    if(!file) return;

    setIsSaving(true);
    try {
        const url = await onUploadImage(file);
        if(url) {
            if(isNew) {
                setNewCategoryIcon(url);
            } else {
                const updated = [...categories];
                updated[index].icon = url;
                setCategories(updated);
                await handleSaveCategories(updated);
            }
        }
    } catch(err) {
        console.error(err);
        alert("Failed to upload image.");
    } finally {
        setIsSaving(false);
    }
  };

  return (
    <div className="space-y-8 animate-fade-in-up pb-20">
      <div className="flex items-center justify-between bg-white dark:bg-slate-900 p-8 rounded-[32px] border shadow-sm">
        <div>
          <h2 className="text-3xl font-black text-slate-800 dark:text-white flex items-center gap-3">
             <ListTree className="text-red-500" size={32} />
             Product Categories
          </h2>
          <p className="text-slate-400 font-medium mt-1">Manage categories and upload icons for your shop.</p>
        </div>
      </div>

      <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm max-w-2xl">
        <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Add New Category</h3>
        <div className="flex flex-col gap-4">
          <div className="flex gap-4 items-center">
            <div className="h-14 w-14 bg-slate-100 rounded-xl border border-slate-300 flex items-center justify-center relative overflow-hidden group shrink-0">
                {newCategoryIcon ? (
                    <img src={newCategoryIcon} alt="Icon" className="w-full h-full object-cover" />
                ) : (
                    <ImageIcon className="text-slate-400" size={24} />
                )}
                <label className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer transition-opacity text-white text-[10px] font-bold text-center p-1">
                    Upload
                    <input type="file" className="hidden" accept="image/*" onChange={(e) => handleIconUpload(e, -1, true)} />
                </label>
            </div>
            <input
              type="text"
              value={newCategoryName}
              onChange={(e) => setNewCategoryName(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleAddCategory()}
              className="flex-1 bg-slate-50 border border-slate-200 px-6 py-4 rounded-2xl focus:ring-2 focus:ring-red-600 outline-none text-lg font-bold"
              placeholder="e.g. Fresh Fruits"
            />
            <button
              onClick={handleAddCategory}
              disabled={isSaving || !newCategoryName.trim()}
              className="h-full bg-red-600 hover:bg-red-700 text-white px-8 py-3.5 rounded-2xl font-black text-sm uppercase tracking-wider shadow-lg shadow-red-600/20 transition-all flex items-center gap-2 disabled:opacity-50"
            >
              {isSaving ? <RefreshCw className="animate-spin" size={20} /> : <Plus size={20} />}
              Add
            </button>
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm max-w-2xl">
        <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">
           Existing Categories <span className="text-slate-400 text-sm ml-2">({categories.length})</span>
        </h3>
        {categories.length === 0 ? (
          <p className="text-slate-400 font-medium text-center py-8">No categories found. Add one above.</p>
        ) : (
          <ul className="space-y-3">
            {categories.map((cat, idx) => (
              <li key={idx} className="flex justify-between items-center bg-slate-50 dark:bg-slate-800 px-6 py-4 rounded-2xl border border-slate-100 dark:border-slate-700 group">
                <div className="flex items-center gap-4">
                    <div className="h-12 w-12 bg-white rounded-lg border flex items-center justify-center relative overflow-hidden group/icon shrink-0">
                        {cat.icon ? (
                            <img src={cat.icon} alt={cat.name} className="w-full h-full object-cover" />
                        ) : (
                            <ImageIcon className="text-slate-300" size={20} />
                        )}
                        <label className="absolute inset-0 bg-black/60 opacity-0 group-hover/icon:opacity-100 flex items-center justify-center cursor-pointer transition-opacity text-white text-[10px] font-bold text-center">
                            Edit
                            <input type="file" className="hidden" accept="image/*" onChange={(e) => handleIconUpload(e, idx, false)} disabled={isSaving} />
                        </label>
                    </div>
                    <span className="font-bold text-lg text-slate-800 dark:text-slate-200">{cat.name}</span>
                </div>
                <button
                  onClick={() => handleDeleteCategory(cat.name)}
                  disabled={isSaving}
                  className="text-slate-400 hover:text-red-500 hover:bg-red-50 p-2 rounded-xl transition-all"
                  title="Delete category"
                >
                  <Trash2 size={20} />
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>

    </div>
  );
};

export default CategoryManager;
