'use client';

import { useState, useEffect } from 'react';
import { X, Search, FileText, Plus } from 'lucide-react';
import { motion } from 'framer-motion';

interface Props {
  onClose: () => void;
  onCreated: () => void;
  partePreseleccionado?: { id: string; numero: number; descripcion: string; clienteId?: string; clienteNombre?: string };
}

export default function NuevoPresupuestoModal({ onClose, onCreated, partePreseleccionado }: Props) {
  const [descripcion, setDescripcion] = useState('');
  const [importeEstimado, setImporteEstimado] = useState('');
  const [clienteSearch, setClienteSearch] = useState('');
  const [clienteId, setClienteId] = useState<string | null>(null);
  const [clienteNombre, setClienteNombre] = useState<string | null>(null);
  const [clienteResults, setClienteResults] = useState<{ id: string; nombre: string }[]>([]);
  const [parteId, setParteId] = useState<string | null>(partePreseleccionado?.id || null);
  const [error, setError] = useState('');
  const [saving, setSaving] = useState(false);

  // Pre-rellenar datos del parte
  useEffect(() => {
    if (partePreseleccionado) {
      if (partePreseleccionado.clienteId) {
        setClienteId(partePreseleccionado.clienteId);
        setClienteNombre(partePreseleccionado.clienteNombre || null);
        setClienteSearch(partePreseleccionado.clienteNombre || '');
      }
    }
  }, [partePreseleccionado]);

  // Búsqueda de clientes
  useEffect(() => {
    if (clienteSearch.length < 2 || clienteId) { setClienteResults([]); return; }
    const t = setTimeout(async () => {
      try {
        const res = await fetch(`/api/clientes/search?q=${encodeURIComponent(clienteSearch)}`);
        if (res.ok) setClienteResults(await res.json());
      } catch { /* ignore */ }
    }, 300);
    return () => clearTimeout(t);
  }, [clienteSearch, clienteId]);

  const selectCliente = (c: { id: string; nombre: string }) => {
    setClienteId(c.id);
    setClienteNombre(c.nombre);
    setClienteSearch(c.nombre);
    setClienteResults([]);
  };

  const clearCliente = () => {
    setClienteId(null);
    setClienteNombre(null);
    setClienteSearch('');
  };

  const handleSubmit = async () => {
    if (!descripcion.trim()) { setError('La descripción es obligatoria'); return; }
    setSaving(true);
    setError('');
    try {
      const res = await fetch('/api/presupuestos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          descripcion,
          parteId,
          clienteId,
          clienteNombre: clienteId ? clienteNombre : (clienteSearch || null),
          importeEstimado: importeEstimado || null,
        }),
      });
      if (res.ok) {
        onCreated();
      } else {
        const err = await res.json();
        setError(err.error || 'Error al crear');
      }
    } catch { setError('Error de conexión'); }
    setSaving(false);
  };

  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={onClose}>
      <motion.div initial={{ scale: 0.95 }} animate={{ scale: 1 }} exit={{ scale: 0.95 }}
        className="bg-white rounded-2xl shadow-xl w-full max-w-lg" 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 flex items-center gap-2">
            <FileText className="w-5 h-5 text-blue-600" />
            Nuevo Presupuesto
          </h2>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded-lg">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        <div className="px-6 py-4 space-y-4">
          {error && <div className="bg-red-50 text-red-700 text-sm px-3 py-2 rounded-lg">{error}</div>}

          {/* Parte vinculada */}
          {partePreseleccionado && (
            <div className="bg-blue-50 rounded-lg px-3 py-2">
              <p className="text-xs text-blue-600 font-medium">Vinculado a parte</p>
              <p className="text-sm text-blue-900">#{partePreseleccionado.numero} · {partePreseleccionado.descripcion}</p>
            </div>
          )}

          {/* Descripción */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Descripción del presupuesto *</label>
            <textarea
              value={descripcion}
              onChange={e => setDescripcion(e.target.value)}
              rows={3}
              placeholder="Ej: Pedir precio de correa para split Daikin FTXS35..."
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Cliente */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Cliente</label>
            {clienteId ? (
              <div className="flex items-center gap-2 bg-blue-50 rounded-lg px-3 py-2">
                <span className="text-sm text-blue-900 flex-1">{clienteNombre}</span>
                <button onClick={clearCliente} className="text-xs text-blue-600 hover:text-blue-800">Cambiar</button>
              </div>
            ) : (
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  value={clienteSearch}
                  onChange={e => setClienteSearch(e.target.value)}
                  placeholder="Buscar cliente..."
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500"
                />
                {clienteResults.length > 0 && (
                  <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 rounded-lg shadow-lg mt-1 z-20 max-h-40 overflow-y-auto">
                    {clienteResults.map(c => (
                      <button key={c.id} onClick={() => selectCliente(c)}
                        className="w-full text-left px-3 py-2 hover:bg-gray-50 text-sm">
                        {c.nombre}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Importe estimado */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Importe estimado (opcional)</label>
            <div className="flex items-center gap-2">
              <input
                type="number"
                step="0.01"
                value={importeEstimado}
                onChange={e => setImporteEstimado(e.target.value)}
                placeholder="0.00"
                className="w-40 border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500"
              />
              <span className="text-sm text-gray-500">{"\u20AC"}</span>
            </div>
          </div>
        </div>

        <div className="px-6 py-4 border-t flex justify-end gap-3">
          <button onClick={onClose} className="px-4 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50">
            Cancelar
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving}
            className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
          >
            <Plus className="w-4 h-4" /> {saving ? 'Creando...' : 'Crear Presupuesto'}
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}
