import type { FC } from 'react';
import { useEffect, useState } from 'react';
import { Star, Edit2, Check, X, Plus, Clock, Tag } from 'lucide-react';
import Layout from '../components/Layout';
import {
  Card,
  Button,
  Input,
  TextArea,
  Modal,
  EmptyState,
  PageHeader,
  Skeleton,
  toast,
} from '../components/ui';
import { odooApi, type Service } from '../services/odoo';

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 [editing, setEditing] = useState<Service | null>(null);
  const [editPrice, setEditPrice] = useState('');
  const [createOpen, setCreateOpen] = useState(false);

  const [form, setForm] = useState({
    name: '',
    code: '',
    category: '',
    price: '',
    duration_min: '',
    description: '',
    color: '#78716c',
    service_group: '',
  });

  const load = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await odooApi.getServices();
      if (res.status === 'success') setServices(res.services);
    } catch (err) {
      setError('Error al cargar servicios');
      toast.error('Error al cargar servicios');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  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 startEdit = (s: Service) => {
    setEditing(s);
    setEditPrice(String(s.price));
  };

  const savePrice = async () => {
    if (!editing) return;
    const price = parseFloat(editPrice);
    if (Number.isNaN(price) || price < 0) {
      toast.error('Precio inválido');
      return;
    }
    try {
      await odooApi.updateService(editing.id, { price });
      toast.success('Precio actualizado');
      setEditing(null);
      await load();
    } catch (err) {
      toast.error('Error al actualizar precio');
      console.error(err);
    }
  };

  const create = async () => {
    const price = parseFloat(form.price);
    const duration = parseInt(form.duration_min, 10);
    if (!form.name || Number.isNaN(price) || price < 0) {
      toast.error('Nombre y precio válidos son obligatorios');
      return;
    }
    try {
      setSubmitting(true);
      await odooApi.createService({
        name: form.name,
        code: form.code,
        category: form.category,
        price,
        duration_min: Number.isNaN(duration) ? 0 : duration,
        description: form.description,
        color: form.color,
        service_group: form.service_group,
      });
      toast.success('Servicio creado');
      setCreateOpen(false);
      setForm({
        name: '',
        code: '',
        category: '',
        price: '',
        duration_min: '',
        description: '',
        color: '#78716c',
        service_group: '',
      });
      await load();
    } catch (err) {
      toast.error('Error al crear servicio');
      console.error(err);
    } finally {
      setSubmitting(false);
    }
  };

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

      {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-40 w-full" />)}
        </div>
      ) : services.length === 0 ? (
        <EmptyState
          title="Sin servicios"
          subtitle="No hay servicios registrados."
          actionLabel="Nuevo servicio"
          onAction={() => setCreateOpen(true)}
        />
      ) : (
        <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-homenest-bark pr-2 truncate">{s.name}</h4>
                  </div>
                  <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-[#E9D5B7]'}
                      fill={s.is_favorite ? 'currentColor' : 'none'}
                    />
                  </Button>
                </div>
                <div className="flex flex-wrap items-center gap-2 text-xs text-[#7A5C44] mb-4">
                  <span className="inline-flex items-center bg-[#FEF3C7] rounded-md px-2 py-0.5">
                    <Tag size={12} className="mr-1" />
                    {s.category || 'Sin categoría'}
                  </span>
                  <span className="inline-flex items-center bg-[#FEF3C7] rounded-md px-2 py-0.5">
                    <Clock size={12} className="mr-1" />
                    {s.duration_min} min
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  {editing?.id === s.id ? (
                    <div className="flex items-center gap-2">
                      <Input
                        type="number"
                        value={editPrice}
                        onChange={(e) => setEditPrice(e.target.value)}
                        className="w-28"
                      />
                      <Button variant="ghost" size="sm" onClick={savePrice} title="Guardar">
                        <Check size={16} className="text-#3E2C1C" />
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => setEditing(null)} title="Cancelar">
                        <X size={16} className="text-[#7A5C44]" />
                      </Button>
                    </div>
                  ) : (
                    <p className="text-lg font-heading font-semibold text-homenest-bark">${s.price}</p>
                  )}
                  <Button variant="ghost" size="sm" onClick={() => startEdit(s)} title="Editar precio">
                    <Edit2 size={16} className="text-[#7A5C44]" />
                  </Button>
                </div>
              </Card.Body>
            </Card>
          ))}
        </div>
      )}

      <Modal
        isOpen={createOpen}
        onClose={() => setCreateOpen(false)}
        title="Nuevo servicio"
        maxWidth="md"
        footer={
          <>
            <Button variant="outline" onClick={() => setCreateOpen(false)}>Cancelar</Button>
            <Button onClick={create} loading={submitting}>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 })}
            />
            <Input
              label="Categoría"
              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 *"
              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>
          <Input
            label="Color"
            type="color"
            value={form.color}
            onChange={(e) => setForm({ ...form, color: e.target.value })}
          />
          <TextArea
            label="Descripción"
            value={form.description}
            onChange={(e) => setForm({ ...form, description: e.target.value })}
          />
        </div>
      </Modal>
    </Layout>
  );
};

export default Servicios;
