'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { motion } from 'framer-motion';
import { X, AlertTriangle, Loader2, Search, Building2, User } from 'lucide-react';
import { CANAL_LABELS, URGENCIA_LABELS } from '@/lib/avisos/constants';

interface ClienteOption {
  id: string;
  nombre: string;
  cif: string | null;
  telefono: string | null;
  tipo: string;
}

interface ContactoOption {
  id: string;
  nombre: string;
  cargo: string | null;
  telefono: string | null;
  email: string | null;
  esPrincipal: boolean;
}

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

export default function NuevoAvisoModal({ onClose, onCreated }: Props) {
  // Form state
  const [form, setForm] = useState({
    cliente: '',
    clienteId: '' as string,
    contacto: '',
    contactoId: '' as string,
    telefono: '',
    canal: 'TELEFONO',
    urgencia: 'NORMAL',
    descripcion: '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [duplicadoWarning, setDuplicadoWarning] = useState<{ message: string; avisoExistenteId: string } | null>(null);

  // Client search autocomplete state
  const [clienteQuery, setClienteQuery] = useState('');
  const [clienteResults, setClienteResults] = useState<ClienteOption[]>([]);
  const [searchingClientes, setSearchingClientes] = useState(false);
  const [showClienteDropdown, setShowClienteDropdown] = useState(false);
  const [selectedCliente, setSelectedCliente] = useState<ClienteOption | null>(null);
  const clienteInputRef = useRef<HTMLInputElement>(null);
  const clienteDropdownRef = useRef<HTMLDivElement>(null);

  // Contactos state
  const [contactos, setContactos] = useState<ContactoOption[]>([]);
  const [loadingContactos, setLoadingContactos] = useState(false);

  // Debounced search for clients
  const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const searchClientes = useCallback(async (query: string) => {
    if (query.length < 2) {
      setClienteResults([]);
      setShowClienteDropdown(false);
      return;
    }
    setSearchingClientes(true);
    try {
      const res = await fetch(`/api/clientes/search?q=${encodeURIComponent(query)}`);
      if (res.ok) {
        const data = await res.json();
        setClienteResults(data);
        setShowClienteDropdown(data.length > 0);
      }
    } catch {
      // silently fail
    } finally {
      setSearchingClientes(false);
    }
  }, []);

  const handleClienteInputChange = (value: string) => {
    setClienteQuery(value);
    setForm(prev => ({ ...prev, cliente: value, clienteId: '', contacto: '', contactoId: '', telefono: '' }));
    setSelectedCliente(null);
    setContactos([]);

    if (searchTimeoutRef.current) clearTimeout(searchTimeoutRef.current);
    searchTimeoutRef.current = setTimeout(() => searchClientes(value), 300);
  };

  const handleSelectCliente = (c: ClienteOption) => {
    setSelectedCliente(c);
    setClienteQuery(c.nombre);
    setForm(prev => ({
      ...prev,
      cliente: c.nombre,
      clienteId: c.id,
      telefono: '',
      contacto: '',
      contactoId: '',
    }));
    setShowClienteDropdown(false);
    setClienteResults([]);
    // Load contacts for this client
    fetchContactos(c.id);
  };

  const fetchContactos = async (clienteId: string) => {
    setLoadingContactos(true);
    try {
      const res = await fetch(`/api/clientes/${clienteId}/contactos`);
      if (res.ok) {
        const data = await res.json();
        setContactos(data);
        // Auto-select principal contact if exists
        const principal = data.find((c: ContactoOption) => c.esPrincipal);
        if (principal) {
          setForm(prev => ({
            ...prev,
            contacto: principal.nombre,
            contactoId: principal.id,
            telefono: principal.telefono || prev.telefono,
          }));
        }
      }
    } catch {
      // silently fail
    } finally {
      setLoadingContactos(false);
    }
  };

  const handleSelectContacto = (contactoId: string) => {
    if (!contactoId) {
      setForm(prev => ({ ...prev, contacto: '', contactoId: '', telefono: '' }));
      return;
    }
    const c = contactos.find(ct => ct.id === contactoId);
    if (c) {
      setForm(prev => ({
        ...prev,
        contacto: c.nombre,
        contactoId: c.id,
        telefono: c.telefono || prev.telefono,
      }));
    }
  };

  // Close dropdown on outside click
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        clienteDropdownRef.current &&
        !clienteDropdownRef.current.contains(e.target as Node) &&
        clienteInputRef.current &&
        !clienteInputRef.current.contains(e.target as Node)
      ) {
        setShowClienteDropdown(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSubmit = async (forzar = false) => {
    setError('');
    if (!form.cliente.trim() || !form.descripcion.trim()) {
      setError('Cliente y descripción son obligatorios');
      return;
    }
    setLoading(true);
    try {
      const res = await fetch('/api/avisos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, forzarCreacion: forzar }),
      });
      const data = await res.json();

      if (res.status === 409 && data.warning === 'posible_duplicado') {
        setDuplicadoWarning({ message: data.message, avisoExistenteId: data.avisoExistenteId });
        setLoading(false);
        return;
      }

      if (!res.ok) {
        setError(data.error || 'Error al crear aviso');
        setLoading(false);
        return;
      }

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

  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 }}
        className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-lg font-bold text-gray-900">Nuevo Aviso</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X className="w-5 h-5" /></button>
        </div>

        <div className="p-6 space-y-4">
          {error && (
            <div className="bg-red-50 text-red-700 p-3 rounded-lg text-sm flex items-center gap-2">
              <AlertTriangle className="w-4 h-4" /> {error}
            </div>
          )}

          {duplicadoWarning && (
            <div className="bg-amber-50 border border-amber-200 p-4 rounded-lg">
              <p className="text-sm text-amber-800 mb-3">
                <AlertTriangle className="w-4 h-4 inline mr-1" />
                {duplicadoWarning.message}
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => handleSubmit(true)}
                  className="text-xs bg-amber-600 text-white px-3 py-1.5 rounded-lg hover:bg-amber-700"
                >
                  Crear de todas formas
                </button>
                <button
                  onClick={() => setDuplicadoWarning(null)}
                  className="text-xs bg-gray-200 text-gray-700 px-3 py-1.5 rounded-lg hover:bg-gray-300"
                >
                  Cancelar
                </button>
              </div>
            </div>
          )}

          {/* Campo Cliente con Autocomplete */}
          <div className="relative">
            <label className="block text-sm font-medium text-gray-700 mb-1">Cliente *</label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                ref={clienteInputRef}
                type="text"
                value={clienteQuery}
                onChange={(e) => handleClienteInputChange(e.target.value)}
                onFocus={() => { if (clienteResults.length > 0) setShowClienteDropdown(true); }}
                placeholder="Escriba para buscar cliente..."
                className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none text-gray-900"
              />
              {searchingClientes && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-gray-400" />}
            </div>
            {selectedCliente && (
              <div className="mt-1 flex items-center gap-2 text-xs text-green-700 bg-green-50 px-2 py-1 rounded">
                <Building2 className="w-3 h-3" />
                <span>{selectedCliente.nombre}</span>
                {selectedCliente.cif && <span className="text-green-600">CIF: {selectedCliente.cif}</span>}
                <button
                  onClick={() => { setSelectedCliente(null); setClienteQuery(''); setForm(prev => ({ ...prev, cliente: '', clienteId: '', contacto: '', contactoId: '', telefono: '' })); setContactos([]); }}
                  className="ml-auto text-green-600 hover:text-green-800"
                >
                  <X className="w-3 h-3" />
                </button>
              </div>
            )}
            {showClienteDropdown && (
              <div ref={clienteDropdownRef} className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto">
                {clienteResults.map((c) => (
                  <button
                    key={c.id}
                    onClick={() => handleSelectCliente(c)}
                    className="w-full text-left px-3 py-2 hover:bg-blue-50 flex items-center gap-2 text-sm border-b border-gray-50 last:border-0"
                  >
                    <Building2 className="w-4 h-4 text-gray-400 flex-shrink-0" />
                    <div className="min-w-0">
                      <p className="font-medium text-gray-900 truncate">{c.nombre}</p>
                      <p className="text-xs text-gray-500">
                        {c.cif && `CIF: ${c.cif}`}
                        {c.cif && c.telefono && ' · '}
                        {c.telefono && `Tel: ${c.telefono}`}
                      </p>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Contacto: desplegable si hay cliente seleccionado con contactos */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Contacto</label>
              {selectedCliente && contactos.length > 0 ? (
                <div className="relative">
                  <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <select
                    value={form.contactoId}
                    onChange={(e) => handleSelectContacto(e.target.value)}
                    className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-lg text-sm bg-white text-gray-900 focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none"
                  >
                    <option value="">-- Seleccionar contacto --</option>
                    {contactos.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.nombre}{c.cargo ? ` (${c.cargo})` : ''}{c.esPrincipal ? ' ★' : ''}
                      </option>
                    ))}
                  </select>
                  {loadingContactos && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-gray-400" />}
                </div>
              ) : (
                <input
                  type="text"
                  value={form.contacto}
                  onChange={(e) => setForm({ ...form, contacto: e.target.value })}
                  placeholder="Persona que llama"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none text-gray-900"
                />
              )}
              {selectedCliente && contactos.length === 0 && !loadingContactos && (
                <p className="text-xs text-gray-400 mt-1">Sin contactos registrados para este cliente</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Teléfono</label>
              <input
                type="text"
                value={form.telefono}
                onChange={(e) => setForm({ ...form, telefono: e.target.value })}
                placeholder="Número de contacto"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none text-gray-900"
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Canal</label>
              <select
                value={form.canal}
                onChange={(e) => setForm({ ...form, canal: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white text-gray-900"
              >
                {Object.entries(CANAL_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">Urgencia</label>
              <select
                value={form.urgencia}
                onChange={(e) => setForm({ ...form, urgencia: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white text-gray-900"
              >
                {Object.entries(URGENCIA_LABELS).map(([k, v]) => (
                  <option key={k} value={k}>{v}</option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Descripción *</label>
            <textarea
              value={form.descripcion}
              onChange={(e) => setForm({ ...form, descripcion: e.target.value })}
              placeholder="Descripción detallada del problema o solicitud"
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none resize-none text-gray-900"
            />
          </div>
        </div>

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