'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Search, RefreshCw, FileText, Plus, ChevronRight,
  MessageSquare, Clock, CheckCircle2, XCircle, Send, Truck,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import PresupuestoDetailModal from './presupuesto-detail-modal';
import NuevoPresupuestoModal from './nuevo-presupuesto-modal';
import {
  ESTADO_LABELS,
  ESTADO_COLORS,
} from '@/lib/presupuestos/constants';

interface Presupuesto {
  id: string;
  numero: number;
  estado: string;
  descripcion: string;
  clienteNombre: string | null;
  importeEstimado: number | null;
  createdAt: string;
  updatedAt: string;
  parte: { id: string; numero: number; tipo: string; descripcion: string } | null;
  clienteRef: { id: string; nombre: string } | null;
  creadoPor: { id: string; name: string } | null;
  _count: { notas: number };
}

const ESTADO_ICONS: Record<string, React.ElementType> = {
  PENDIENTE: Clock,
  SOLICITADO_PROVEEDOR: Truck,
  ENVIADO_CLIENTE: Send,
  ACEPTADO: CheckCircle2,
  RECHAZADO: XCircle,
};

export default function PresupuestosContent({ userRole }: { userRole: string }) {
  const [presupuestos, setPresupuestos] = useState<Presupuesto[]>([]);
  const [total, setTotal] = useState(0);
  const [contadores, setContadores] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [estadoFilter, setEstadoFilter] = useState('TODOS');
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [showNuevo, setShowNuevo] = useState(false);

  const canEdit = userRole === 'admin' || userRole === 'oficina';

  const fetchPresupuestos = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (estadoFilter !== 'TODOS') params.set('estado', estadoFilter);
      if (search) params.set('search', search);

      const res = await fetch(`/api/presupuestos?${params}`);
      if (res.ok) {
        const data = await res.json();
        setPresupuestos(data.presupuestos);
        setTotal(data.total);
        setContadores(data.contadores);
      }
    } catch { /* ignore */ }
    setLoading(false);
  }, [estadoFilter, search]);

  useEffect(() => {
    const timer = setTimeout(fetchPresupuestos, 300);
    return () => clearTimeout(timer);
  }, [fetchPresupuestos]);

  const totalPendientes = (contadores['PENDIENTE'] || 0) + (contadores['SOLICITADO_PROVEEDOR'] || 0) + (contadores['ENVIADO_CLIENTE'] || 0);

  const FILTROS_ESTADO = [
    { key: 'TODOS', label: 'Todos' },
    { key: 'PENDIENTE', label: 'Pendientes' },
    { key: 'SOLICITADO_PROVEEDOR', label: 'Solicitados' },
    { key: 'ENVIADO_CLIENTE', label: 'Enviados' },
    { key: 'ACEPTADO', label: 'Aceptados' },
    { key: 'RECHAZADO', label: 'Rechazados' },
  ];

  return (
    <div>
      {/* Cabecera */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Pendientes de Presupuesto</h1>
          <p className="text-sm text-gray-500">
            {totalPendientes} pendiente{totalPendientes !== 1 ? 's' : ''} de resolver · {total} total
          </p>
        </div>
        {canEdit && (
          <button
            onClick={() => setShowNuevo(true)}
            className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition text-sm font-medium"
          >
            <Plus className="w-4 h-4" /> Nuevo Pendiente
          </button>
        )}
      </div>

      {/* Resumen por estados */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
        {FILTROS_ESTADO.filter(f => f.key !== 'TODOS').map(f => {
          const Icon = ESTADO_ICONS[f.key] || FileText;
          const count = contadores[f.key] || 0;
          const isActive = estadoFilter === f.key;
          return (
            <button
              key={f.key}
              onClick={() => setEstadoFilter(isActive ? 'TODOS' : f.key)}
              className={`p-3 rounded-lg border text-left transition ${
                isActive
                  ? 'border-blue-400 bg-blue-50 ring-1 ring-blue-300'
                  : 'border-gray-200 bg-white hover:border-gray-300'
              }`}
            >
              <div className="flex items-center gap-2 mb-1">
                <Icon className="w-4 h-4 text-gray-500" />
                <span className="text-xs text-gray-500">{f.label}</span>
              </div>
              <span className="text-xl font-bold text-gray-900">{count}</span>
            </button>
          );
        })}
      </div>

      {/* Búsqueda */}
      <div className="flex items-center gap-3 mb-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Buscar por descripción, cliente, número..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
        <button
          onClick={fetchPresupuestos}
          className="p-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition"
          title="Refrescar"
        >
          <RefreshCw className={`w-4 h-4 text-gray-500 ${loading ? 'animate-spin' : ''}`} />
        </button>
      </div>

      {/* Filtros rápidos de estado (pills) */}
      <div className="flex gap-2 mb-4 flex-wrap">
        {FILTROS_ESTADO.map(f => (
          <button
            key={f.key}
            onClick={() => setEstadoFilter(f.key)}
            className={`px-3 py-1 rounded-full text-xs font-medium transition ${
              estadoFilter === f.key
                ? 'bg-blue-600 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {f.label}
            {f.key !== 'TODOS' && contadores[f.key] ? ` (${contadores[f.key]})` : ''}
          </button>
        ))}
      </div>

      {/* Lista */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {loading ? (
          <div className="flex justify-center py-12">
            <RefreshCw className="w-6 h-6 text-gray-400 animate-spin" />
          </div>
        ) : presupuestos.length === 0 ? (
          <div className="text-center py-12">
            <FileText className="w-10 h-10 text-gray-300 mx-auto mb-2" />
            <p className="text-gray-500">No se encontraron presupuestos pendientes</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {presupuestos.map(p => {
              const Icon = ESTADO_ICONS[p.estado] || FileText;
              return (
                <button
                  key={p.id}
                  onClick={() => setSelectedId(p.id)}
                  className="w-full text-left px-4 py-3 hover:bg-gray-50 transition flex items-center gap-3"
                >
                  <div className={`p-2 rounded-lg ${ESTADO_COLORS[p.estado] || 'bg-gray-100 text-gray-600'}`}>
                    <Icon className="w-4 h-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-mono text-gray-400">#{p.numero}</span>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${ESTADO_COLORS[p.estado] || 'bg-gray-100 text-gray-600'}`}>
                        {ESTADO_LABELS[p.estado] || p.estado}
                      </span>
                      {p._count.notas > 0 && (
                        <span className="flex items-center gap-0.5 text-xs text-gray-400">
                          <MessageSquare className="w-3 h-3" />
                          {p._count.notas}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-900 truncate mt-0.5">{p.descripcion}</p>
                    <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
                      {(p.clienteRef?.nombre || p.clienteNombre) && (
                        <span>Cliente: {p.clienteRef?.nombre || p.clienteNombre}</span>
                      )}
                      {p.parte && <span>Parte #{p.parte.numero}</span>}
                      {p.importeEstimado != null && <span>{p.importeEstimado.toFixed(2)}{'\u20AC'}</span>}
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    <p className="text-xs text-gray-400">
                      {new Date(p.createdAt).toLocaleDateString('es-ES', { day: '2-digit', month: 'short' })}
                    </p>
                    <ChevronRight className="w-4 h-4 text-gray-300 mt-1 ml-auto" />
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* Modales */}
      <AnimatePresence>
        {selectedId && (
          <PresupuestoDetailModal
            id={selectedId}
            canEdit={canEdit}
            onClose={() => setSelectedId(null)}
            onUpdated={fetchPresupuestos}
          />
        )}
        {showNuevo && (
          <NuevoPresupuestoModal
            onClose={() => setShowNuevo(false)}
            onCreated={() => { setShowNuevo(false); fetchPresupuestos(); }}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
