import type { FC } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { Star, Wallet, Edit2, Plus, Clock, Tag, Package, Search } from 'lucide-react';
import Layout from '../components/Layout';
import {
  Card,
  Button,
  Input,
  Select,
  TextArea,
  Modal,
  EmptyState,
  PageHeader,
  Skeleton,
  toast,
} from '../components/ui';
import { useSearchParams } from 'react-router-dom';
import { odooApi, type Service } from '../services/odoo';

const categoryOptions = [
  { value: '', label: 'Todas las categorías' },
  { value: 'consulta', label: 'Consulta' },
  { value: 'tratamiento', label: 'Tratamiento' },
  { value: 'procedimiento', label: 'Procedimiento' },
  { value: 'paquete', label: 'Paquete' },
];

const categoryFormOptions = categoryOptions.filter((o) => o.value !== '');

const categoryLabels: Record<string, string> = {
  consulta: 'Consulta',
  tratamiento: 'Tratamiento',
  procedimiento: 'Procedimiento',
  paquete: 'Paquete',
};

interface ServiceForm {
  name: string;
  code: string;
  category: string;
  price: string;
  package_price: string;
  package_sessions: string;
  package_notes: string;
  duration_min: string;
  description: string;
  color: string;
  service_group: string;
}

const emptyForm: ServiceForm = {
  name: '',
  code: '',
  category: 'tratamiento',
  price: '',
  package_price: '',
  package_sessions: '',
  package_notes: '',
  duration_min: '30',
  description: '',
  color: '#EDA588',
  service_group: '',
};

const Servicios: FC = () => {
  const [services, setServices] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchParams] = useSearchParams();
  const [search, setSearch] = useState(() => searchParams.get('q') || '');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const pageSize = 60;

  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Service | null>(null);
  const [form, setForm] = useState<ServiceForm>(emptyForm);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await odooApi.getServices({
        search: search || undefined,
        category: categoryFilter || undefined,
        page,
        page_size: pageSize,
      });
      if (res.status === 'success') {
        setServices(res.services);
        setTotal(res.total ?? 0);
        setTotalPages(res.total_pages ?? 0);
      }
    } catch (err) {
      setError('Error al cargar servicios');
      toast.error('Error al cargar servicios');
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [search, categoryFilter, page]);

  useEffect(() => {
    const t = setTimeout(load, 250);
    return () => clearTimeout(t);
  }, [load]);

  useEffect(() => {
    setPage(1);
  }, [search, categoryFilter]);

  const toggleFavorite = async (s: Service) => {
    try {
      await odooApi.updateService(s.id, { is_favorite: !s.is_favorite });
      toast.success('Favorito actualizado');
      await load();
    } catch (err) {
      toast.error('Error al actualizar favorito');
      console.error(err);
    }
  };

  const toggleMonedero = async (s: Service) => {
    try {
      await odooApi.updateService(s.id, { genera_monedero: s.genera_monedero === false });
      toast.success(s.genera_monedero === false ? 'El servicio ahora genera monedero' : 'El servicio ya no genera monedero');
      await load();
    } catch (err) {
      toast.error('Error al actualizar monedero');
      console.error(err);
    }
  };

  const openCreate = () => {
    setEditing(null);
    setForm(emptyForm);
    setModalOpen(true);
  };

  const openEdit = (s: Service) => {
    setEditing(s);
    setForm({
      name: s.name,
      code: s.code || '',
      category: s.category || 'tratamiento',
      price: String(s.price),
      package_price: s.package_price ? String(s.package_price) : '',
      package_sessions: s.package_sessions ? String(s.package_sessions) : '',
      package_notes: s.package_notes || '',
      duration_min: String(s.duration_min),
      description: s.description || '',
      color: s.color || '#EDA588',
      service_group: s.service_group || '',
    });
    setModalOpen(true);
  };

  const deactivate = async () => {
    if (!editing) return;
    if (!window.confirm(`¿Desactivar "${editing.name}"? Dejará de aparecer en el catálogo y en los selectores de citas/ventas.`)) return;
    try {
      setSubmitting(true);
      await odooApi.updateService(editing.id, { active: false } as Partial<Service>);
      toast.success('Servicio desactivado');
      setModalOpen(false);
      setEditing(null);
      await load();
    } catch (err) {
      toast.error('Error al desactivar servicio');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const save = async () => {
    const price = parseFloat(form.price);
    const duration = parseInt(form.duration_min, 10);
    const packagePrice = form.package_price === '' ? 0 : parseFloat(form.package_price);
    const packageSessions = form.package_sessions === '' ? 0 : parseInt(form.package_sessions, 10);
    if (!form.name.trim()) {
      toast.error('El nombre es obligatorio');
      return;
    }
    if (Number.isNaN(price) || price < 0) {
      toast.error('Precio inválido');
      return;
    }
    if (form.category === 'paquete' && (Number.isNaN(packageSessions) || packageSessions <= 0)) {
      toast.error('Un paquete debe tener al menos 1 sesión');
      return;
    }
    const payload: Partial<Service> = {
      name: form.name.trim(),
      code: form.code.trim(),
      category: form.category,
      price,
      package_price: Number.isNaN(packagePrice) ? 0 : packagePrice,
      package_sessions: Number.isNaN(packageSessions) ? 0 : packageSessions,
      package_notes: form.package_notes,
      duration_min: Number.isNaN(duration) ? 30 : duration,
      description: form.description,
      color: form.color,
      service_group: form.service_group,
    };
    try {
      setSubmitting(true);
      if (editing) {
        await odooApi.updateService(editing.id, payload);
        toast.success('Servicio actualizado');
      } else {
        await odooApi.createService(payload);
        toast.success('Servicio creado');
      }
      setModalOpen(false);
      setEditing(null);
      await load();
    } catch (err) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || (editing ? 'Error al actualizar servicio' : 'Error al crear servicio'));
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

  const formatCurrency = (value: number) =>
    new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 }).format(value);

  return (
    <Layout title="Servicios" subtitle="Catálogo de tratamientos">
      <PageHeader title="Servicios" subtitle="Gestiona precios, paquetes y favoritos">
        <Button onClick={openCreate}>
          <Plus size={16} className="mr-2" />
          Nuevo servicio
        </Button>
      </PageHeader>

      <div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-4 sm:mb-6">
        <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 código..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select
          options={categoryOptions}
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
          className="sm:max-w-[200px]"
        />
      </div>

      {error && <p className="text-rose-600 text-sm mb-4">{error}</p>}

      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => <Skeleton key={i} className="h-48 w-full" />)}
        </div>
      ) : services.length === 0 ? (
        <EmptyState
          title="Sin servicios"
          subtitle={search || categoryFilter ? 'No hay servicios que coincidan con los filtros.' : 'No hay servicios registrados.'}
          actionLabel="Nuevo servicio"
          onAction={openCreate}
        />
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {services.map((s) => (
              <Card key={s.id} className="hover:shadow-md transition">
                <Card.Body>
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-center gap-2 min-w-0">
                      <div
                        className="w-3 h-3 rounded-full shrink-0"
                        style={{ backgroundColor: s.color || '#78716c' }}
                      />
                      <h4 className="font-medium text-theme-heading pr-2 truncate">{s.name}</h4>
                    </div>
                    <div className="flex items-center shrink-0">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => toggleMonedero(s)}
                        title={s.genera_monedero === false ? 'No genera monedero — clic para activar' : 'Genera monedero — clic para desactivar'}
                      >
                        <Wallet
                          size={18}
                          className={s.genera_monedero === false ? 'text-theme-muted opacity-50' : 'text-theme-accent'}
                        />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => toggleFavorite(s)}
                        title={s.is_favorite ? 'Quitar favorito' : 'Marcar favorito'}
                      >
                        <Star
                          size={18}
                          className={s.is_favorite ? 'text-amber-500' : 'text-theme-muted'}
                          fill={s.is_favorite ? 'currentColor' : 'none'}
                        />
                      </Button>
                    </div>
                  </div>
                  <div className="flex flex-wrap items-center gap-2 text-xs text-theme-muted mb-4">
                    <span className="inline-flex items-center bg-theme-bg rounded-md px-2 py-0.5">
                      <Tag size={12} className="mr-1" />
                      {categoryLabels[s.category] || s.category || 'Sin categoría'}
                    </span>
                    <span className="inline-flex items-center bg-theme-bg rounded-md px-2 py-0.5">
                      <Clock size={12} className="mr-1" />
                      {s.duration_min} min
                    </span>
                    {s.code && (
                      <span className="inline-flex items-center bg-theme-bg rounded-md px-2 py-0.5">
                        {s.code}
                      </span>
                    )}
                  </div>

                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-xs text-theme-muted">Precio sesión</p>
                        <p className="text-lg font-heading font-semibold text-theme-heading">{formatCurrency(s.price)}</p>
                      </div>
                      <Button variant="ghost" size="sm" onClick={() => openEdit(s)} title="Editar">
                        <Edit2 size={16} className="text-theme-muted" />
                      </Button>
                    </div>
                    {(s.package_price ?? 0) > 0 && (s.package_sessions ?? 0) > 0 && (
                      <div className="flex items-start gap-2 rounded-xl p-2.5" style={{ backgroundColor: 'var(--success)' }}>
                        <Package size={14} className="shrink-0 mt-0.5" style={{ color: 'var(--success-text)' }} />
                        <div>
                          <p className="text-xs font-medium" style={{ color: 'var(--success-text)' }}>
                            Paquete {s.package_sessions} sesiones: {formatCurrency(s.package_price ?? 0)}
                          </p>
                          {s.package_notes && <p className="text-[10px]" style={{ color: 'var(--success-text)' }}>{s.package_notes}</p>}
                        </div>
                      </div>
                    )}
                  </div>
                </Card.Body>
              </Card>
            ))}
          </div>

          {/* Paginación */}
          <div className="flex flex-col sm:flex-row items-center justify-between gap-3 mt-4 pt-4 border-t border-theme-border">
            <p className="text-sm text-theme-muted">
              {total} servicios · página {page} de {totalPages || 1}
            </p>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => Math.max(1, p - 1))}>
                Anterior
              </Button>
              <Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>
                Siguiente
              </Button>
            </div>
          </div>
        </>
      )}

      {/* Modal crear/editar */}
      <Modal
        isOpen={modalOpen}
        onClose={() => { setModalOpen(false); setEditing(null); }}
        title={editing ? `Editar: ${editing.name}` : 'Nuevo servicio'}
        maxWidth="lg"
        footer={
          <>
            {editing && (
              <Button variant="danger" onClick={deactivate} loading={submitting} className="sm:mr-auto">
                Desactivar
              </Button>
            )}
            <Button variant="outline" onClick={() => { setModalOpen(false); setEditing(null); }}>Cancelar</Button>
            <Button onClick={save} loading={submitting}>{editing ? 'Guardar cambios' : 'Crear servicio'}</Button>
          </>
        }
      >
        <div className="space-y-4">
          <Input
            label="Nombre *"
            value={form.name}
            onChange={(e) => setForm({ ...form, name: e.target.value })}
          />
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="Código"
              value={form.code}
              onChange={(e) => setForm({ ...form, code: e.target.value })}
              placeholder="Ej. DEP-AXI"
            />
            <Select
              label="Categoría *"
              options={categoryFormOptions}
              value={form.category}
              onChange={(e) => setForm({ ...form, category: e.target.value })}
            />
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="Precio sesión *"
              type="number"
              value={form.price}
              onChange={(e) => setForm({ ...form, price: e.target.value })}
            />
            <Input
              label="Duración (min)"
              type="number"
              value={form.duration_min}
              onChange={(e) => setForm({ ...form, duration_min: e.target.value })}
            />
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="Precio paquete"
              type="number"
              value={form.package_price}
              onChange={(e) => setForm({ ...form, package_price: e.target.value })}
            />
            <Input
              label="Sesiones en paquete"
              type="number"
              value={form.package_sessions}
              onChange={(e) => setForm({ ...form, package_sessions: e.target.value })}
            />
          </div>
          <Input
            label="Notas del paquete"
            value={form.package_notes}
            onChange={(e) => setForm({ ...form, package_notes: e.target.value })}
          />
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Input
              label="Grupo"
              value={form.service_group}
              onChange={(e) => setForm({ ...form, service_group: e.target.value })}
              placeholder="Ej. Faciales, Corporales"
            />
            <Input
              label="Color"
              type="color"
              value={form.color}
              onChange={(e) => setForm({ ...form, color: e.target.value })}
            />
          </div>
          <TextArea
            label="Descripción"
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
          />
          <p className="text-xs text-theme-muted">
            Si el nombre o código ya existen en el catálogo, el sistema lo rechazará para evitar duplicados.
          </p>
        </div>
      </Modal>
    </Layout>
  );
};

export default Servicios;
