'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Search, Plus, Building2, Phone, MapPin,
  ChevronLeft, ChevronRight, Eye,
  RefreshCw
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { TIPO_LABELS, TIPO_COLORS } from '@/lib/clientes/constants';
import NuevoClienteModal from './nuevo-cliente-modal';
import ClienteDetailModal from './cliente-detail-modal';

interface Props {
  userRole?: string;
}

export default function ClientesContent({ userRole = 'operario' }: Props) {
  const canEdit = userRole === 'admin' || userRole === 'oficina';

  const [clientes, setClientes] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [tipoFilter, setTipoFilter] = useState('');
  const [activoFilter, setActivoFilter] = useState('true');
  const [page, setPage] = useState(1);
  const limit = 25;

  const [showNuevo, setShowNuevo] = useState(false);
  const [selectedClienteId, setSelectedClienteId] = useState<string | null>(null);

  const fetchClientes = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) params.set('search', search);
      if (tipoFilter) params.set('tipo', tipoFilter);
      if (activoFilter) params.set('activo', activoFilter);
      params.set('page', page.toString());
      params.set('limit', limit.toString());

      const res = await fetch(`/api/clientes?${params}`);
      const data = await res.json();
      setClientes(data.clientes || []);
      setTotal(data.total || 0);
    } catch (e) {
      console.error('Error fetching clientes:', e);
    } finally {
      setLoading(false);
    }
  }, [search, tipoFilter, activoFilter, page]);

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

  const totalPages = Math.ceil(total / limit);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Clientes</h1>
          <p className="text-sm text-gray-500 mt-1">{total} cliente{total !== 1 ? 's' : ''} encontrado{total !== 1 ? 's' : ''}</p>
        </div>
        <div className="flex gap-2">
          <button
            onClick={fetchClientes}
            className="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition flex items-center gap-2 text-gray-700"
          >
            <RefreshCw className="w-4 h-4" />
          </button>
          {canEdit && (
            <button
              onClick={() => setShowNuevo(true)}
              className="px-4 py-2 text-sm bg-[#1a365d] text-white rounded-lg hover:bg-[#2d4a7c] transition flex items-center gap-2"
            >
              <Plus className="w-4 h-4" /> Nuevo cliente
            </button>
          )}
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl border border-gray-200 p-4">
        <div className="flex flex-col sm:flex-row gap-3">
          <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 nombre, CIF, teléfono, dirección..."
              value={search}
              onChange={(e) => { setSearch(e.target.value); setPage(1); }}
              className="w-full pl-10 pr-4 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none"
            />
          </div>
          <select
            value={tipoFilter}
            onChange={(e) => { setTipoFilter(e.target.value); setPage(1); }}
            className="px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none bg-white"
          >
            <option value="">Todos los tipos</option>
            {Object.entries(TIPO_LABELS).map(([k, v]) => (
              <option key={k} value={k}>{v}</option>
            ))}
          </select>
          <select
            value={activoFilter}
            onChange={(e) => { setActivoFilter(e.target.value); setPage(1); }}
            className="px-3 py-2.5 text-sm border border-gray-200 rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none bg-white"
          >
            <option value="true">Activos</option>
            <option value="false">Inactivos</option>
            <option value="">Todos</option>
          </select>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {loading ? (
          <div className="p-12 text-center text-gray-400">
            <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
            Cargando clientes...
          </div>
        ) : clientes.length === 0 ? (
          <div className="p-12 text-center text-gray-400">
            <Building2 className="w-8 h-8 mx-auto mb-2 opacity-50" />
            No se encontraron clientes
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50 border-b border-gray-200">
                  <th className="text-left px-4 py-3 font-semibold text-gray-600">Cliente</th>
                  <th className="text-left px-4 py-3 font-semibold text-gray-600 hidden md:table-cell">CIF</th>
                  <th className="text-left px-4 py-3 font-semibold text-gray-600 hidden sm:table-cell">Tipo</th>
                  <th className="text-left px-4 py-3 font-semibold text-gray-600 hidden lg:table-cell">Contacto principal</th>
                  <th className="text-left px-4 py-3 font-semibold text-gray-600 hidden lg:table-cell">Teléfono</th>
                  <th className="text-left px-4 py-3 font-semibold text-gray-600 hidden xl:table-cell">Dirección</th>
                  <th className="text-center px-4 py-3 font-semibold text-gray-600 w-20">Ver</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {clientes.map((c: any) => {
                  const contactoPrincipal = c.contactos?.[0];
                  const direccionPrincipal = c.direcciones?.[0];
                  return (
                    <tr
                      key={c.id}
                      className="hover:bg-gray-50 transition cursor-pointer"
                      onClick={() => setSelectedClienteId(c.id)}
                    >
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div className={`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold ${!c.activo ? 'bg-gray-200 text-gray-500' : 'bg-[#1a365d]/10 text-[#1a365d]'}`}>
                            {c.nombre?.charAt(0)?.toUpperCase()}
                          </div>
                          <div>
                            <div className={`font-medium ${!c.activo ? 'text-gray-400 line-through' : 'text-gray-900'}`}>{c.nombre}</div>
                            {c.email && <div className="text-xs text-gray-400">{c.email}</div>}
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-gray-600 hidden md:table-cell">{c.cif || '—'}</td>
                      <td className="px-4 py-3 hidden sm:table-cell">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${TIPO_COLORS[c.tipo] || 'bg-gray-100 text-gray-700'}`}>
                          {TIPO_LABELS[c.tipo] || c.tipo}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-gray-600 hidden lg:table-cell">
                        {contactoPrincipal ? contactoPrincipal.nombre : '—'}
                      </td>
                      <td className="px-4 py-3 text-gray-600 hidden lg:table-cell">
                        {contactoPrincipal?.telefono || c.telefono || '—'}
                      </td>
                      <td className="px-4 py-3 text-gray-500 text-xs hidden xl:table-cell max-w-[200px] truncate">
                        {direccionPrincipal
                          ? `${direccionPrincipal.calle}${direccionPrincipal.numero ? ' ' + direccionPrincipal.numero : ''}, ${direccionPrincipal.ciudad || ''}`
                          : '—'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <button
                          onClick={(e) => { e.stopPropagation(); setSelectedClienteId(c.id); }}
                          className="p-1.5 hover:bg-gray-100 rounded-lg transition"
                        >
                          <Eye className="w-4 h-4 text-gray-500" />
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-gray-200 bg-gray-50">
            <span className="text-xs text-gray-500">Página {page} de {totalPages}</span>
            <div className="flex gap-1">
              <button
                disabled={page <= 1}
                onClick={() => setPage(p => p - 1)}
                className="p-1.5 rounded hover:bg-gray-200 disabled:opacity-30 transition"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <button
                disabled={page >= totalPages}
                onClick={() => setPage(p => p + 1)}
                className="p-1.5 rounded hover:bg-gray-200 disabled:opacity-30 transition"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Modals */}
      <AnimatePresence>
        {showNuevo && (
          <NuevoClienteModal
            onClose={() => setShowNuevo(false)}
            onCreated={() => { setShowNuevo(false); fetchClientes(); }}
          />
        )}
      </AnimatePresence>

      <AnimatePresence>
        {selectedClienteId && (
          <ClienteDetailModal
            clienteId={selectedClienteId}
            canEdit={canEdit}
            onClose={() => setSelectedClienteId(null)}
            onUpdated={fetchClientes}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
