'use client';

import { useState } from 'react';
import { X, Plus, Trash2, AlertTriangle, Loader2 } from 'lucide-react';
import { motion } from 'framer-motion';
import { TIPO_LABELS, TIPO_DIRECCION_LABELS, FORMAS_PAGO_LABELS } from '@/lib/clientes/constants';

interface Props {
  onClose: () => void;
  onCreated: () => void;
}

interface ContactoForm {
  nombre: string;
  cargo: string;
  telefono: string;
  email: string;
  esPrincipal: boolean;
}

interface DireccionForm {
  tipo: string;
  calle: string;
  numero: string;
  piso: string;
  codigoPostal: string;
  ciudad: string;
  provincia: string;
  esPrincipal: boolean;
}

export default function NuevoClienteModal({ onClose, onCreated }: Props) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [duplicados, setDuplicados] = useState<any[]>([]);
  const [showDupWarning, setShowDupWarning] = useState(false);

  const [nombre, setNombre] = useState('');
  const [cif, setCif] = useState('');
  const [tipo, setTipo] = useState('EMPRESA');
  const [email, setEmail] = useState('');
  const [telefono, setTelefono] = useState('');
  const [web, setWeb] = useState('');
  const [observaciones, setObservaciones] = useState('');
  const [formaPago, setFormaPago] = useState('TRANSFERENCIA_BANCARIA');

  const [contactos, setContactos] = useState<ContactoForm[]>([
    { nombre: '', cargo: '', telefono: '', email: '', esPrincipal: true },
  ]);

  const [direcciones, setDirecciones] = useState<DireccionForm[]>([
    { tipo: 'PRINCIPAL', calle: '', numero: '', piso: '', codigoPostal: '', ciudad: '', provincia: '', esPrincipal: true },
  ]);

  const [tab, setTab] = useState<'general' | 'contactos' | 'direcciones'>('general');

  const addContacto = () => {
    setContactos(prev => [...prev, { nombre: '', cargo: '', telefono: '', email: '', esPrincipal: false }]);
  };

  const removeContacto = (i: number) => {
    setContactos(prev => prev.filter((_, idx) => idx !== i));
  };

  const updateContacto = (i: number, field: keyof ContactoForm, value: any) => {
    setContactos(prev => prev.map((c, idx) => idx === i ? { ...c, [field]: value } : c));
  };

  const addDireccion = () => {
    setDirecciones(prev => [...prev, { tipo: 'OTRO', calle: '', numero: '', piso: '', codigoPostal: '', ciudad: '', provincia: '', esPrincipal: false }]);
  };

  const removeDireccion = (i: number) => {
    setDirecciones(prev => prev.filter((_, idx) => idx !== i));
  };

  const updateDireccion = (i: number, field: keyof DireccionForm, value: any) => {
    setDirecciones(prev => prev.map((d, idx) => idx === i ? { ...d, [field]: value } : d));
  };

  const handleSubmit = async (forzar = false) => {
    setError('');
    if (!nombre.trim()) { setError('El nombre es obligatorio'); return; }

    setLoading(true);
    try {
      const validContactos = contactos.filter(c => c.nombre.trim());
      const validDirecciones = direcciones.filter(d => d.calle.trim());

      const res = await fetch('/api/clientes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          nombre, cif: cif || undefined, tipo, email: email || undefined,
          telefono: telefono || undefined, web: web || undefined,
          observaciones: observaciones || undefined,
          formaPago,
          contactos: validContactos.length > 0 ? validContactos : undefined,
          direcciones: validDirecciones.length > 0 ? validDirecciones : undefined,
          forzar,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        if (data.requiereForzar && data.duplicados) {
          setDuplicados(data.duplicados);
          setShowDupWarning(true);
          return;
        }
        setError(data.error || 'Error al crear cliente');
        return;
      }

      onCreated();
    } catch (e) {
      setError('Error de conexión');
    } finally {
      setLoading(false);
    }
  };

  const tabs = [
    { key: 'general', label: 'General' },
    { key: 'contactos', label: `Contactos (${contactos.length})` },
    { key: 'direcciones', label: `Direcciones (${direcciones.length})` },
  ] as const;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        onClick={(e) => e.stopPropagation()}
        className="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col"
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-lg font-bold text-gray-900">Nuevo cliente</h2>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b px-6">
          {tabs.map(t => (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              className={`px-4 py-2.5 text-sm font-medium border-b-2 transition ${tab === t.key ? 'border-[#1a365d] text-[#1a365d]' : 'border-transparent text-gray-500 hover:text-gray-700'
                }`}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          {/* Duplicate warning */}
          {showDupWarning && (
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <AlertTriangle className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium text-amber-800">Posible duplicado detectado</p>
                  <ul className="mt-2 space-y-1">
                    {duplicados.map((d: any) => (
                      <li key={d.id} className="text-sm text-amber-700">
                        • <strong>{d.nombre}</strong> (similitud: {Math.round(d.score * 100)}%)
                      </li>
                    ))}
                  </ul>
                  <div className="mt-3 flex gap-2">
                    <button
                      onClick={() => handleSubmit(true)}
                      className="px-3 py-1.5 text-xs bg-amber-600 text-white rounded-lg hover:bg-amber-700"
                    >
                      Crear de todas formas
                    </button>
                    <button
                      onClick={() => setShowDupWarning(false)}
                      className="px-3 py-1.5 text-xs bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
                    >
                      Cancelar
                    </button>
                  </div>
                </div>
              </div>
            </div>
          )}

          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-2 rounded-lg text-sm">{error}</div>
          )}

          {/* Tab: General */}
          {tab === 'general' && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="sm:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Nombre / Razón social *</label>
                  <input value={nombre} onChange={e => setNombre(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" placeholder="Ej: Farmacia El Pinar S.L." />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">CIF / NIF</label>
                  <input value={cif} onChange={e => setCif(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" placeholder="B12345678" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                  <select value={tipo} onChange={e => setTipo(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none bg-white">
                    {Object.entries(TIPO_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Teléfono</label>
                  <input value={telefono} onChange={e => setTelefono(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Web</label>
                  <input value={web} onChange={e => setWeb(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" placeholder="https://" />
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Forma de Pago Habitual</label>
                  <select value={formaPago} onChange={e => setFormaPago(e.target.value)} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none bg-white">
                    {Object.entries(FORMAS_PAGO_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                  </select>
                </div>
                <div className="sm:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">Observaciones internas</label>
                  <textarea value={observaciones} onChange={e => setObservaciones(e.target.value)} rows={3} className="w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none resize-none" />
                </div>
              </div>
            </div>
          )}

          {/* Tab: Contactos */}
          {tab === 'contactos' && (
            <div className="space-y-4">
              {contactos.map((c, i) => (
                <div key={i} className="border rounded-lg p-4 space-y-3 bg-gray-50">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-700">Contacto {i + 1} {c.esPrincipal && <span className="text-xs text-blue-600">(Principal)</span>}</span>
                    {contactos.length > 1 && (
                      <button onClick={() => removeContacto(i)} className="p-1 hover:bg-red-50 text-red-500 rounded">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <input value={c.nombre} onChange={e => updateContacto(i, 'nombre', e.target.value)} placeholder="Nombre *" className="px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                    <input value={c.cargo} onChange={e => updateContacto(i, 'cargo', e.target.value)} placeholder="Cargo" className="px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                    <input value={c.telefono} onChange={e => updateContacto(i, 'telefono', e.target.value)} placeholder="Teléfono" className="px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                    <input value={c.email} onChange={e => updateContacto(i, 'email', e.target.value)} placeholder="Email" className="px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                  </div>
                  <label className="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
                    <input type="checkbox" checked={c.esPrincipal} onChange={e => updateContacto(i, 'esPrincipal', e.target.checked)} className="rounded" />
                    Contacto principal
                  </label>
                </div>
              ))}
              <button onClick={addContacto} className="flex items-center gap-2 text-sm text-[#1a365d] hover:underline">
                <Plus className="w-4 h-4" /> Añadir contacto
              </button>
            </div>
          )}

          {/* Tab: Direcciones */}
          {tab === 'direcciones' && (
            <div className="space-y-4">
              {direcciones.map((d, i) => (
                <div key={i} className="border rounded-lg p-4 space-y-3 bg-gray-50">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-700">Dirección {i + 1} {d.esPrincipal && <span className="text-xs text-blue-600">(Principal)</span>}</span>
                    {direcciones.length > 1 && (
                      <button onClick={() => removeDireccion(i)} className="p-1 hover:bg-red-50 text-red-500 rounded">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    )}
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <select value={d.tipo} onChange={e => updateDireccion(i, 'tipo', e.target.value)} className="px-3 py-2 text-sm border rounded-lg outline-none bg-white">
                      {Object.entries(TIPO_DIRECCION_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                    </select>
                    <input value={d.calle} onChange={e => updateDireccion(i, 'calle', e.target.value)} placeholder="Calle *" className="sm:col-span-2 px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-[#1a365d]/20 focus:border-[#1a365d] outline-none" />
                    <input value={d.numero} onChange={e => updateDireccion(i, 'numero', e.target.value)} placeholder="Número" className="px-3 py-2 text-sm border rounded-lg outline-none" />
                    <input value={d.piso} onChange={e => updateDireccion(i, 'piso', e.target.value)} placeholder="Piso / Puerta" className="px-3 py-2 text-sm border rounded-lg outline-none" />
                    <input value={d.codigoPostal} onChange={e => updateDireccion(i, 'codigoPostal', e.target.value)} placeholder="C.P." className="px-3 py-2 text-sm border rounded-lg outline-none" />
                    <input value={d.ciudad} onChange={e => updateDireccion(i, 'ciudad', e.target.value)} placeholder="Ciudad" className="px-3 py-2 text-sm border rounded-lg outline-none" />
                    <input value={d.provincia} onChange={e => updateDireccion(i, 'provincia', e.target.value)} placeholder="Provincia" className="px-3 py-2 text-sm border rounded-lg outline-none" />
                  </div>
                  <label className="flex items-center gap-2 text-sm text-gray-600 cursor-pointer">
                    <input type="checkbox" checked={d.esPrincipal} onChange={e => updateDireccion(i, 'esPrincipal', e.target.checked)} className="rounded" />
                    Dirección principal
                  </label>
                </div>
              ))}
              <button onClick={addDireccion} className="flex items-center gap-2 text-sm text-[#1a365d] hover:underline">
                <Plus className="w-4 h-4" /> Añadir dirección
              </button>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 px-6 py-4 border-t bg-gray-50">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-200 rounded-lg transition">
            Cancelar
          </button>
          <button
            onClick={() => handleSubmit(false)}
            disabled={loading}
            className="px-5 py-2 text-sm bg-[#1a365d] text-white rounded-lg hover:bg-[#2d4a7c] transition disabled:opacity-50 flex items-center gap-2"
          >
            {loading && <Loader2 className="w-4 h-4 animate-spin" />}
            Crear cliente
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}
