'use client';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Plus, Edit, Trash2, FolderOpen } from 'lucide-react';
import { useLanguage } from '@/lib/i18n/language-context';

export default function CategoriesPage() {
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState({ name: '', nameEn: '', description: '', order: 0, parentId: '' });
  const { t } = useLanguage();

  const fetchCategories = async () => {
    try {
      const res = await fetch('/api/categories');
      const data = await res?.json?.() ?? [];
      setCategories(Array.isArray(data) ? data : []);
    } catch {} finally { setLoading(false); }
  };

  useEffect(() => { fetchCategories(); }, []);

  const handleSubmit = async (e: any) => {
    e?.preventDefault?.();
    if (!form?.name) return;
    try {
      const url = editingId ? `/api/categories/${editingId}` : '/api/categories';
      const method = editingId ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (res?.ok) {
        toast?.success?.(editingId ? t.admin.categories.updated : t.admin.categories.created);
        setForm({ name: '', nameEn: '', description: '', order: 0, parentId: '' });
        setShowForm(false);
        setEditingId(null);
        fetchCategories();
      }
    } catch { toast?.error?.(t.admin.categories.error); }
  };

  const handleEdit = (cat: any) => {
    setForm({ name: cat?.name ?? '', nameEn: cat?.nameEn ?? '', description: cat?.description ?? '', order: cat?.order ?? 0, parentId: cat?.parentId ?? '' });
    setEditingId(cat?.id);
    setShowForm(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm(t.admin.categories.deleteConfirm)) return;
    try {
      await fetch(`/api/categories/${id}`, { method: 'DELETE' });
      toast?.success?.(t.admin.categories.deleted);
      fetchCategories();
    } catch { toast?.error?.(t.admin.categories.deleteError); }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="font-display text-2xl font-bold tracking-tight">{t.admin.categories.title}</h1>
        <button onClick={() => { setShowForm(!showForm); setEditingId(null); setForm({ name: '', nameEn: '', description: '', order: 0, parentId: '' }); }} className="bg-red-600 hover:bg-red-700 text-white px-5 py-2.5 rounded-lg text-sm font-semibold transition flex items-center gap-2">
          <Plus className="w-4 h-4" /> {t.admin.categories.addNew}
        </button>
      </div>

      {showForm && (
        <form onSubmit={handleSubmit} className="bg-white rounded-xl shadow-sm p-6 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.categories.name} (ES) *</label>
              <input type="text" required value={form?.name ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), name: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.categories.name} (EN)</label>
              <input type="text" value={form?.nameEn ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), nameEn: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" placeholder="English name" />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.categories.description}</label>
              <input type="text" value={form?.description ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), description: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-1 block">{t.admin.categories.order}</label>
              <input type="number" value={form?.order ?? 0} onChange={(e: any) => setForm({ ...(form ?? {}), order: parseInt(e?.target?.value ?? '0') })} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm" />
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-1 block">Categoría Padre</label>
              <select value={form?.parentId ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), parentId: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm">
                <option value="">Ninguna (categoría principal)</option>
                {(categories ?? [])?.filter((c: any) => !c?.parentId && c?.id !== editingId)?.map((c: any) => (
                  <option key={c?.id} value={c?.id}>{c?.name}</option>
                ))}
              </select>
            </div>
          </div>
          <div className="mt-4 flex gap-2">
            <button type="submit" className="bg-red-600 hover:bg-red-700 text-white px-6 py-2.5 rounded-lg text-sm font-semibold transition">
              {t.admin.categories.save}
            </button>
            <button type="button" onClick={() => { setShowForm(false); setEditingId(null); }} className="px-6 py-2.5 rounded-lg text-sm text-gray-600 hover:bg-gray-100 transition">
              {t.admin.categories.cancel}
            </button>
          </div>
        </form>
      )}

      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex justify-center py-10"><div className="animate-spin w-6 h-6 border-3 border-red-600 border-t-transparent rounded-full" /></div>
        ) : (categories?.length ?? 0) > 0 ? (
          <table className="w-full">
            <thead className="bg-gray-50 text-xs text-gray-500 uppercase">
              <tr>
                <th className="px-4 py-3 text-left">{t.admin.categories.name}</th>
                <th className="px-4 py-3 text-left">{t.admin.categories.description}</th>
                <th className="px-4 py-3 text-center">{t.admin.categories.vehicles}</th>
                <th className="px-4 py-3 text-center">{t.admin.categories.order}</th>
                <th className="px-4 py-3 text-right">{t.admin.categories.actions}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {(categories ?? [])?.map((cat: any) => (
                <tr key={cat?.id} className="hover:bg-gray-50 transition">
                  <td className="px-4 py-3 text-sm font-medium text-gray-900">
                    <div className="flex items-center gap-2">
                      {cat?.parentId && <span className="text-gray-300 ml-4">└</span>}
                      <FolderOpen className="w-4 h-4 text-red-500" />
                      <div>
                        <span>{cat?.name ?? ''}</span>
                        {cat?.nameEn && <span className="text-gray-400 text-xs ml-1">({cat.nameEn})</span>}
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-500">{cat?.description ?? '-'}</td>
                  <td className="px-4 py-3 text-sm text-center text-gray-500">{cat?._count?.vehicles ?? 0}</td>
                  <td className="px-4 py-3 text-sm text-center text-gray-500">{cat?.order ?? 0}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-2">
                      <button onClick={() => handleEdit(cat)} className="p-2 text-gray-400 hover:text-blue-600 transition"><Edit className="w-4 h-4" /></button>
                      <button onClick={() => handleDelete(cat?.id)} className="p-2 text-gray-400 hover:text-red-600 transition"><Trash2 className="w-4 h-4" /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="text-center py-12">
            <FolderOpen className="w-12 h-12 text-gray-300 mx-auto mb-3" />
            <p className="text-gray-400">{t.admin.dashboard.noData}</p>
          </div>
        )}
      </div>
    </div>
  );
}