import { useState, useEffect } from 'react';
import { clientService } from '../../services/clientService';
import {
  User, Search, Phone, Mail, CreditCard,
  Edit, MapPin, ExternalLink,
  BarChart3, Award, Clock
} from 'lucide-react';
import Modal from '../../components/Modal';
import { useNavigate } from 'react-router-dom';

interface Client {
  id: number;
  name: string;
  dniOrCuit: string;
  email?: string;
  phone?: string;
  address?: string;
  totalAds: number;
  totalSpent: number;
}

export default function ClientManager() {
  const navigate = useNavigate();
  const [clients, setClients] = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  // Estados para Modales
  const [selectedClient, setSelectedClient] = useState<any>(null);
  const [summary, setSummary] = useState<any>(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showSummaryModal, setShowSummaryModal] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

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

  const loadClients = async () => {
    setLoading(true);
    try {
      const res = await clientService.getAll();
      setClients(res);
    } finally {
      setLoading(false);
    }
  };

  const handleOpenSummary = async (client: Client) => {
    setSummary(null);
    setSelectedClient(client);
    setShowSummaryModal(true);
    const data = await clientService.getSummary(client.id);
    setSummary(data);
  };

  const handleOpenEdit = (client: Client) => {
    setSelectedClient({ ...client });
    setShowEditModal(true);
  };

  const handleSaveEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedClient) return;
    setIsSaving(true);
    try {
      await clientService.update(selectedClient.id, selectedClient);
      await loadClients();
      setShowEditModal(false);
    } finally {
      setIsSaving(false);
    }
  };

  const filteredClients = clients.filter(c => {
    const name = (c.name || "").toLowerCase();
    const dni = (c.dniOrCuit || "").toLowerCase();
    const s = search.toLowerCase();
    return name.includes(s) || dni.includes(s);
  });

  return (
    <div className="space-y-6">
      <header className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-2">
            <User className="text-blue-600" /> Directorio de Clientes
          </h2>
          <p className="text-sm text-gray-500">Gestión de datos fiscales y analítica de anunciantes</p>
        </div>
      </header>

      <div className="bg-white p-4 rounded-xl border shadow-sm relative">
        <Search className="absolute left-7 top-7 text-gray-400" size={20} />
        <input
          type="text"
          placeholder="Filtrar por nombre o identificación..."
          className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 transition-all"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {loading ? (
          <div className="col-span-full py-20 text-center animate-pulse text-gray-400 font-bold uppercase text-xs tracking-widest">
            Sincronizando base de datos...
          </div>
        ) : filteredClients.map(client => (
          <div key={client.id} className="bg-white rounded-2xl border border-gray-200 shadow-sm hover:shadow-md transition-all overflow-hidden group">
            <div className="p-5 border-b border-gray-50 bg-gray-50/50">
              <div className="flex justify-between items-start">
                <div className="w-10 h-10 bg-blue-600 text-white rounded-xl flex items-center justify-center font-bold text-lg">
                  {(client.name || "?").charAt(0).toUpperCase()}
                </div>
                <button
                  onClick={() => handleOpenEdit(client)}
                  className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                >
                  <Edit size={18} />
                </button>
              </div>
              <h3 className="mt-3 font-bold text-gray-800 text-lg line-clamp-1 uppercase tracking-tight">{client.name}</h3>
              <div className="flex items-center gap-1.5 text-xs text-gray-400 font-bold mt-1">
                <CreditCard size={14} /> {client.dniOrCuit}
              </div>
            </div>

            <div className="p-5 space-y-3">
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <Mail size={16} className="text-gray-300" /> {client.email || 'N/A'}
              </div>
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <Phone size={16} className="text-gray-300" /> {client.phone || 'N/A'}
              </div>

              <div className="grid grid-cols-2 gap-2 mt-4 pt-4 border-t border-gray-50">
                <div className="text-center border-r border-gray-50">
                  <div className="text-[9px] text-gray-400 font-black uppercase tracking-tighter">Avisos</div>
                  <div className="text-lg font-black text-slate-800">{client.totalAds}</div>
                </div>
                <div className="text-center">
                  <div className="text-[9px] text-gray-400 font-black uppercase tracking-tighter">Invertido</div>
                  <div className="text-lg font-black text-emerald-600">${client.totalSpent?.toLocaleString()}</div>
                </div>
              </div>
            </div>

            <button
              onClick={() => handleOpenSummary(client)}
              className="w-full py-3.5 bg-white text-blue-600 text-[10px] font-black uppercase tracking-[0.2em] hover:bg-blue-600 hover:text-white transition-all flex items-center justify-center gap-2 border-t"
            >
              <BarChart3 size={14} /> Ficha del Anunciante
            </button>
          </div>
        ))}
      </div>

      {/* --- MODAL DE EDICIÓN / FACTURACIÓN --- */}
      <Modal isOpen={showEditModal} onClose={() => setShowEditModal(false)} title="Datos Fiscales y de Contacto">
        <form onSubmit={handleSaveEdit} className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="md:col-span-2">
              <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">Razón Social / Nombre</label>
              <input
                type="text" required
                className="w-full border-2 border-gray-100 p-2.5 rounded-xl font-bold focus:border-blue-500 outline-none transition-all"
                value={selectedClient?.name || ""}
                onChange={e => setSelectedClient({ ...selectedClient!, name: e.target.value })}
              />
            </div>
            <div>
              <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">DNI / CUIT</label>
              <input
                type="text" required
                className="w-full border-2 border-gray-100 p-2.5 rounded-xl font-bold focus:border-blue-500 outline-none transition-all"
                value={selectedClient?.dniOrCuit || ""}
                onChange={e => setSelectedClient({ ...selectedClient!, dniOrCuit: e.target.value })}
              />
            </div>
            <div>
              <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">Teléfono</label>
              <input
                type="text"
                className="w-full border-2 border-gray-100 p-2.5 rounded-xl font-bold focus:border-blue-500 outline-none transition-all"
                value={selectedClient?.phone || ""}
                onChange={e => setSelectedClient({ ...selectedClient!, phone: e.target.value })}
              />
            </div>
            <div className="md:col-span-2">
              <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">Email</label>
              <input
                type="email"
                className="w-full border-2 border-gray-100 p-2.5 rounded-xl font-bold focus:border-blue-500 outline-none transition-all"
                value={selectedClient?.email || ""}
                onChange={e => setSelectedClient({ ...selectedClient!, email: e.target.value })}
              />
            </div>
            <div className="md:col-span-2">
              <label className="text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">Dirección de Facturación</label>
              <div className="relative">
                <MapPin className="absolute left-3 top-3 text-gray-300" size={18} />
                <input
                  type="text"
                  className="w-full border-2 border-gray-100 p-2.5 pl-10 rounded-xl font-bold focus:border-blue-500 outline-none transition-all"
                  value={selectedClient?.address || ""}
                  onChange={e => setSelectedClient({ ...selectedClient!, address: e.target.value })}
                  placeholder="Calle, Nro, Localidad..."
                />
              </div>
            </div>
          </div>
          <div className="flex justify-end gap-3 pt-6">
            <button type="button" onClick={() => setShowEditModal(false)} className="px-6 py-2.5 text-xs font-bold text-gray-500 uppercase tracking-widest">Cancelar</button>
            <button
              type="submit" disabled={isSaving}
              className="bg-blue-600 text-white px-8 py-2.5 rounded-xl font-black text-xs uppercase tracking-widest shadow-lg shadow-blue-200 hover:bg-blue-700 disabled:opacity-50 transition-all"
            >
              {isSaving ? "Actualizando..." : "Guardar Cambios"}
            </button>
          </div>
        </form>
      </Modal>

      {/* --- MODAL DE FICHA INTEGRAL (SUMMARY) --- */}
      <Modal
        isOpen={showSummaryModal}
        onClose={() => setShowSummaryModal(false)}
        title="Perfil de Actividad"
      >
        {summary ? (
          <div className="space-y-6">
            <div className="flex items-center gap-4 bg-slate-900 p-6 rounded-[2rem] text-white shadow-xl relative overflow-hidden">
              <div className="absolute right-0 top-0 p-4 opacity-10"><Award size={100} /></div>
              <div className="w-16 h-16 bg-blue-600 rounded-2xl flex items-center justify-center text-3xl font-black relative z-10">
                {summary.Name.charAt(0)}
              </div>
              <div className="relative z-10">
                <h3 className="text-xl font-black uppercase tracking-tight leading-tight">{summary.Name}</h3>
                <p className="text-[10px] font-bold text-blue-400 uppercase tracking-[0.2em] mt-1">{summary.DniOrCuit}</p>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-emerald-50 border border-emerald-100 rounded-2xl shadow-sm">
                <p className="text-[9px] font-black text-emerald-600 uppercase mb-1 tracking-widest">Inversión Total</p>
                <p className="text-2xl font-black text-emerald-800 tracking-tighter">${summary.TotalInvested.toLocaleString()}</p>
              </div>
              <div className="p-4 bg-blue-50 border border-blue-100 rounded-2xl shadow-sm">
                <p className="text-[9px] font-black text-blue-600 uppercase mb-1 tracking-widest">Avisos Activos</p>
                <p className="text-2xl font-black text-blue-800 tracking-tighter">{summary.ActiveAds}</p>
              </div>
              <div className="p-4 bg-white border border-gray-100 rounded-2xl shadow-sm">
                <p className="text-[9px] font-black text-gray-400 uppercase mb-1 tracking-widest">Avisos Totales</p>
                <p className="text-xl font-bold text-gray-700 tracking-tighter">{summary.TotalAds}</p>
              </div>
              <div className="p-4 bg-white border border-gray-100 rounded-2xl shadow-sm">
                <p className="text-[9px] font-black text-gray-400 uppercase mb-1 tracking-widest">Rubro Predilecto</p>
                <p className="text-xs font-black text-gray-700 uppercase truncate mt-1">{summary.PreferredCategory}</p>
              </div>
            </div>

            <div className="bg-slate-50 p-6 rounded-[2rem] border border-slate-200 space-y-3">
              <div className="flex justify-between items-center text-[10px] font-black uppercase">
                <span className="text-gray-400 tracking-widest flex items-center gap-1.5"><Clock size={14} /> Última Publicación</span>
                <span className="text-slate-800">{summary.LastAdDate ? new Date(summary.LastAdDate).toLocaleDateString() : 'NUNCA'}</span>
              </div>
              <div className="flex justify-between items-center text-[10px] font-black uppercase">
                <span className="text-gray-400 tracking-widest flex items-center gap-1.5"><Mail size={14} /> Email Registrado</span>
                <span className="text-slate-800 truncate max-w-[200px]">{summary.Email || 'S/D'}</span>
              </div>
              <div className="flex justify-between items-center text-[10px] font-black uppercase">
                <span className="text-gray-400 tracking-widest flex items-center gap-1.5"><Phone size={14} /> Teléfono</span>
                <span className="text-slate-800">{summary.Phone || 'S/D'}</span>
              </div>
            </div>

            <button
              onClick={() => {
                navigate(`/listings?q=${summary.DniOrCuit}`);
              }}
              className="w-full py-4 bg-slate-900 hover:bg-black text-white rounded-2xl font-black uppercase text-[10px] tracking-[0.2em] transition-all flex items-center justify-center gap-3 shadow-xl"
            >
              <ExternalLink size={18} className="text-blue-500" /> Consultar Avisos en el Explorador
            </button>
          </div>
        ) : (
          <div className="py-20 text-center flex flex-col items-center gap-4">
            <div className="w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
            <p className="text-slate-400 font-black uppercase text-[10px] tracking-widest">Analizando historial del cliente...</p>
          </div>
        )}
      </Modal>
    </div>
  );
}