import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Plus, Pencil, Trash2, Search, BookMarked } from 'lucide-react';
import {
  Button,
  Input,
  TextArea,
  Modal,
  EmptyState,
  Skeleton,
  MobileCard,
  toast,
} from './ui';
import { odooApi, type Diagnostico, type Procedimiento } from '../services/odoo';

type CatalogoItem = Diagnostico | Procedimiento;

interface CatalogoPanelProps {
  kind: 'diagnosticos' | 'procedimientos';
  titulo: string;
}

const CatalogoPanel: FC<CatalogoPanelProps> = ({ kind, titulo }) => {
  const [items, setItems] = useState<CatalogoItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<CatalogoItem | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({ name: '', categoria: '', descripcion: '' });

  const api = kind === 'diagnosticos'
    ? { list: odooApi.getDiagnosticos, create: odooApi.createDiagnostico, update: odooApi.updateDiagnostico, remove: odooApi.deleteDiagnostico }
    : { list: odooApi.getProcedimientos, create: odooApi.createProcedimiento, update: odooApi.updateProcedimiento, remove: odooApi.deleteProcedimiento };

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await api.list(search || undefined);
      if (res.status === 'success') setItems(res.items);
    } catch (err) {
      toast.error(`Error al cargar ${titulo.toLowerCase()}`);
      console.error(err);
    } finally {
      setLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search, kind]);

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

  const openCreate = () => {
    setEditing(null);
    setForm({ name: '', categoria: '', descripcion: '' });
    setModalOpen(true);
  };

  const openEdit = (item: CatalogoItem) => {
    setEditing(item);
    setForm({ name: item.name, categoria: item.categoria, descripcion: item.descripcion });
    setModalOpen(true);
  };

  const submit = async () => {
    if (!form.name.trim()) {
      toast.error('El nombre es obligatorio');
      return;
    }
    try {
      setSubmitting(true);
      if (editing) {
        await api.update(editing.id, form);
        toast.success('Actualizado');
      } else {
        await api.create(form);
        toast.success('Creado');
      }
      setModalOpen(false);
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al guardar');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const eliminar = async (item: CatalogoItem) => {
    if (!window.confirm(`¿Eliminar "${item.name}"?`)) return;
    try {
      await api.remove(item.id);
      toast.success('Eliminado');
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al eliminar');
      console.error(err);
    }
  };

  return (
    <>
      <div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-4">
        <div className="relative w-full sm:max-w-sm">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-theme-muted" />
          <Input
            placeholder="Buscar por nombre o categoría..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-10"
          />
        </div>
        <Button onClick={openCreate} className="sm:ml-auto">
          <Plus size={16} className="mr-2" />
          Nuevo
        </Button>
      </div>

      {loading ? (
        <Skeleton count={4} className="h-12 w-full" />
      ) : items.length === 0 ? (
        <EmptyState
          title={`Sin ${titulo.toLowerCase()}`}
          subtitle={`Agrega el primero al catálogo de ${titulo.toLowerCase()}.`}
          actionLabel="Nuevo"
          onAction={openCreate}
          icon={<BookMarked size={28} />}
        />
      ) : (
        <>
          <div className="hidden sm:block overflow-x-auto">
            <table className="w-full">
              <thead className="bg-theme-bg">
                <tr>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Nombre</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Categoría</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase hidden md:table-cell">Descripción</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {items.map((item) => (
                  <tr key={item.id} className="hover:bg-theme-bg">
                    <td className="p-3 text-sm font-medium text-theme-heading">{item.name}</td>
                    <td className="p-3 text-sm text-theme-muted">{item.categoria || '-'}</td>
                    <td className="p-3 text-sm text-theme-muted hidden md:table-cell">
                      <span className="block max-w-md truncate">{item.descripcion}</span>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-1">
                        <Button variant="ghost" size="sm" onClick={() => openEdit(item)} title="Editar">
                          <Pencil size={16} className="text-theme-muted" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => eliminar(item)} title="Eliminar">
                          <Trash2 size={16} className="text-rose-500" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="sm:hidden space-y-3">
            {items.map((item) => (
              <MobileCard
                key={item.id}
                title={item.name}
                subtitle={item.categoria || undefined}
                rows={[{ label: 'Descripción', value: item.descripcion.slice(0, 60) || '-' }]}
                actions={
                  <div className="flex items-center gap-1">
                    <Button variant="ghost" size="sm" onClick={() => openEdit(item)}><Pencil size={16} className="text-theme-muted" /></Button>
                    <Button variant="ghost" size="sm" onClick={() => eliminar(item)}><Trash2 size={16} className="text-rose-500" /></Button>
                  </div>
                }
              />
            ))}
          </div>
        </>
      )}

      {/* Modal crear/editar */}
      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editing ? 'Editar' : 'Nuevo'}
        maxWidth="lg"
        footer={
          <>
            <Button variant="outline" onClick={() => setModalOpen(false)}>Cancelar</Button>
            <Button onClick={submit} loading={submitting}>{editing ? 'Guardar' : 'Crear'}</Button>
          </>
        }
      >
        <div className="space-y-4">
          <Input
            label="Nombre *"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
          />
          <Input
            label="Categoría"
            value={form.categoria}
            onChange={(e) => setForm({ ...form, categoria: e.target.value })}
          />
          <TextArea
            label="Descripción"
            value={form.descripcion}
            onChange={(e) => setForm({ ...form, descripcion: e.target.value })}
          />
        </div>
      </Modal>
    </>
  );
};

export default CatalogoPanel;
