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

const RecetasPanel: FC = () => {
  const [recetas, setRecetas] = useState<Receta[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Receta | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({ name: '', categoria: '', contenido: '' });

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await odooApi.getRecetas(search || undefined);
      if (res.status === 'success') setRecetas(res.recetas);
    } catch (err) {
      toast.error('Error al cargar recetas');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [search]);

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

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

  const openEdit = (r: Receta) => {
    setEditing(r);
    setForm({ name: r.name, categoria: r.categoria, contenido: r.contenido });
    setModalOpen(true);
  };

  const submit = async () => {
    if (!form.name.trim() || !form.contenido.trim()) {
      toast.error('Nombre y contenido son obligatorios');
      return;
    }
    try {
      setSubmitting(true);
      if (editing) {
        await odooApi.updateReceta(editing.id, form);
        toast.success('Receta actualizada');
      } else {
        await odooApi.createReceta(form);
        toast.success('Receta creada');
      }
      setModalOpen(false);
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al guardar receta');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const eliminar = async (r: Receta) => {
    if (!window.confirm(`¿Eliminar la receta "${r.name}"?`)) return;
    try {
      await odooApi.deleteReceta(r.id);
      toast.success('Receta eliminada');
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || 'Error al eliminar receta');
      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" />
          Nueva receta
        </Button>
      </div>

      {loading ? (
        <Skeleton count={4} className="h-12 w-full" />
      ) : recetas.length === 0 ? (
        <EmptyState
          title="Sin recetas"
          subtitle="Crea la primera plantilla de receta."
          actionLabel="Nueva receta"
          onAction={openCreate}
          icon={<ScrollText 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">Contenido</th>
                  <th className="text-left p-3 text-xs font-medium text-theme-muted uppercase">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {recetas.map((r) => (
                  <tr key={r.id} className="hover:bg-theme-bg">
                    <td className="p-3 text-sm font-medium text-theme-heading">{r.name}</td>
                    <td className="p-3 text-sm text-theme-muted">{r.categoria || '-'}</td>
                    <td className="p-3 text-sm text-theme-muted hidden md:table-cell">
                      <span className="block max-w-md truncate">{r.contenido}</span>
                    </td>
                    <td className="p-3">
                      <div className="flex items-center gap-1">
                        <Button variant="ghost" size="sm" onClick={() => openEdit(r)} title="Editar">
                          <Pencil size={16} className="text-theme-muted" />
                        </Button>
                        <Button variant="ghost" size="sm" onClick={() => eliminar(r)} title="Eliminar">
                          <Trash2 size={16} className="text-rose-500" />
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

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

      {/* Modal crear/editar receta */}
      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editing ? 'Editar receta' : 'Nueva receta'}
        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 })}
            placeholder="ej. Post-peeling, Antibiótico acné"
          />
          <Input
            label="Categoría"
            value={form.categoria}
            onChange={(e) => setForm({ ...form, categoria: e.target.value })}
            placeholder="ej. Cuidados, Medicamento"
          />
          <TextArea
            label="Contenido * (medicamentos, dosis, indicaciones)"
            value={form.contenido}
            onChange={(e) => setForm({ ...form, contenido: e.target.value })}
          />
        </div>
      </Modal>
    </>
  );
};

export default RecetasPanel;
