'use client';

import { useState, useCallback, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, Loader2, AlertTriangle, Search, Clock, Car, Info } from 'lucide-react';
import { TIPO_EVENTO_LABELS, PRIORIDAD_LABELS } from '@/lib/agenda/constants';

interface Props {
  tecnicos: { id: string; name: string }[];
  preselectedDate: string | null;
  preselectedTecnico: string | null;
  preselectedAvisoId: string | null;
  onClose: () => void;
  onCreated: () => void;
}

interface AvisoOption {
  id: string;
  numero: number;
  cliente: string;
  descripcion: string;
  urgencia: string;
  estado: string;
  telefono?: string | null;
  partes: { id: string; numero: number; descripcion: string; estado: string }[];
}

interface SuggestedSlot {
  horaInicio: string;
  horaFin: string;
  travelMinutes: number;
  marginMinutes: number;
  previousEnd: string;
}

function timeToMinutes(t: string): number {
  const [h, m] = t.split(':').map(Number);
  return h * 60 + m;
}

function minutesToTime(m: number): string {
  const hh = Math.floor(m / 60);
  const mm = m % 60;
  return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
}

export default function NuevoEventoModal({
  tecnicos, preselectedDate, preselectedTecnico, preselectedAvisoId, onClose, onCreated,
}: Props) {
  const todayISO = (() => { const n = new Date(); return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`; })();
  const [form, setForm] = useState({
    titulo: '',
    tipo: 'VISITA_AVISO',
    fecha: preselectedDate || todayISO,
    horaInicio: '09:00',
    horaFin: '10:00',
    duracionMinutos: '',
    todoElDia: false,
    fijado: false,
    notas: '',
    prioridad: 'NORMAL',
    avisoId: '',
    parteId: '',
    tecnicoIds: preselectedTecnico ? [preselectedTecnico] : [] as string[],
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [solapWarning, setSolapWarning] = useState<string | null>(null);
  const [solapFixSlot, setSolapFixSlot] = useState<{ horaInicio: string; horaFin: string } | null>(null);

  // Aviso search
  const [avisoQuery, setAvisoQuery] = useState('');
  const [avisoResults, setAvisoResults] = useState<AvisoOption[]>([]);
  const [searchingAvisos, setSearchingAvisos] = useState(false);
  const [selectedAviso, setSelectedAviso] = useState<AvisoOption | null>(null);

  // Suggested time slot
  const [suggestedSlot, setSuggestedSlot] = useState<SuggestedSlot | null>(null);
  const [calculatingSlot, setCalculatingSlot] = useState(false);
  const [margenDesplazamiento, setMargenDesplazamiento] = useState(10);

  // Fetch configuracion for margenDesplazamiento
  useEffect(() => {
    fetch('/api/configuracion')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data?.config?.margenDesplazamiento) setMargenDesplazamiento(data.config.margenDesplazamiento);
      })
      .catch(() => { });
  }, []);

  // Load preselected aviso
  useEffect(() => {
    if (preselectedAvisoId) {
      loadAvisoById(preselectedAvisoId);
    }
  }, [preselectedAvisoId]);

  // Calculate suggested slot when date or technician changes and auto-apply it
  useEffect(() => {
    if (form.fecha && form.tecnicoIds.length > 0 && !form.todoElDia) {
      calculateSuggestedSlot(form.fecha, form.tecnicoIds[0], true);
    } else {
      setSuggestedSlot(null);
    }
  }, [form.fecha, form.tecnicoIds, margenDesplazamiento]);

  const calculateSuggestedSlot = async (fecha: string, tecnicoId: string, autoApply = false, durationMin = 60, excludeId?: string) => {
    setCalculatingSlot(true);
    try {
      // Get existing events for this technician on this date
      const res = await fetch(`/api/agenda?desde=${fecha}&hasta=${fecha}&tecnicoId=${tecnicoId}`);
      if (!res.ok) { setCalculatingSlot(false); return; }
      const data = await res.json();
      const existingEvents = (data.eventos || [])
        .filter((e: { id?: string; horaFin?: string; todoElDia?: boolean; estado?: string }) =>
          e.horaFin && !e.todoElDia && e.estado !== 'CANCELADO' && (!excludeId || e.id !== excludeId)
        )
        .sort((a: { horaInicio?: string }, b: { horaInicio?: string }) =>
          (a.horaInicio || '').localeCompare(b.horaInicio || '')
        );

      if (existingEvents.length === 0) {
        setSuggestedSlot(null);
        setCalculatingSlot(false);
        return null;
      }

      // Find the last event
      const lastEvent = existingEvents[existingEvents.length - 1];
      const lastEndMin = timeToMinutes(lastEvent.horaFin);

      // Try to get travel time from Google Maps API
      let travelMin = 0;
      try {
        const travelRes = await fetch(`/api/agenda/travel-times?fecha=${fecha}&tecnicoId=${tecnicoId}`);
        if (travelRes.ok) {
          const travelData = await travelRes.json();
          if (travelData.travelTimes && travelData.travelTimes.length > 0) {
            const avgTravel = travelData.travelTimes.reduce(
              (sum: number, t: { durationMinutes: number }) => sum + t.durationMinutes, 0
            ) / travelData.travelTimes.length;
            travelMin = Math.ceil(avgTravel);
          }
        }
      } catch { /* ignore */ }

      // Calculate suggested start: lastEnd + travelTime + margin
      const suggestedStartMin = lastEndMin + travelMin + margenDesplazamiento;
      const suggestedEndMin = suggestedStartMin + durationMin;

      // Don't suggest if it goes past 20:00
      if (suggestedStartMin >= 20 * 60) {
        setSuggestedSlot(null);
        setCalculatingSlot(false);
        return null;
      }

      const slot = {
        horaInicio: minutesToTime(suggestedStartMin),
        horaFin: minutesToTime(Math.min(suggestedEndMin, 20 * 60)),
        travelMinutes: travelMin,
        marginMinutes: margenDesplazamiento,
        previousEnd: lastEvent.horaFin,
      };
      setSuggestedSlot(slot);

      // Auto-apply if requested
      if (autoApply) {
        setForm(prev => ({ ...prev, horaInicio: slot.horaInicio, horaFin: slot.horaFin }));
      }

      setCalculatingSlot(false);
      return slot;
    } catch { /* ignore */ }
    setCalculatingSlot(false);
    return null;
  };

  const applySuggestedSlot = () => {
    if (!suggestedSlot) return;
    setForm(prev => ({
      ...prev,
      horaInicio: suggestedSlot.horaInicio,
      horaFin: suggestedSlot.horaFin,
    }));
  };

  const loadAvisoById = async (avisoId: string) => {
    try {
      const res = await fetch(`/api/avisos/${avisoId}`);
      if (res.ok) {
        const data = await res.json();
        const aviso = data.aviso || data;
        if (aviso && aviso.id) {
          handleSelectAviso({
            id: aviso.id,
            numero: aviso.numero,
            cliente: aviso.cliente,
            descripcion: aviso.descripcion || '',
            urgencia: aviso.urgencia,
            estado: aviso.estado,
            telefono: aviso.telefono,
            partes: aviso.partes || [],
          });
        }
      }
    } catch { /* ignore */ }
  };

  const searchAvisos = useCallback(async (q: string) => {
    if (q.length < 2) { setAvisoResults([]); return; }
    setSearchingAvisos(true);
    try {
      const res = await fetch(`/api/avisos?q=${encodeURIComponent(q)}&limit=10`);
      if (res.ok) {
        const data = await res.json();
        setAvisoResults(data.avisos || []);
      }
    } catch { /* */ }
    setSearchingAvisos(false);
  }, []);

  const handleToggleTecnico = (tid: string) => {
    setForm(prev => ({
      ...prev,
      tecnicoIds: prev.tecnicoIds.includes(tid)
        ? prev.tecnicoIds.filter(id => id !== tid)
        : [...prev.tecnicoIds, tid],
    }));
  };

  const handleSelectAviso = (aviso: AvisoOption) => {
    setSelectedAviso(aviso);
    setForm(prev => ({
      ...prev,
      avisoId: aviso.id,
      tipo: 'VISITA_AVISO',
      titulo: prev.titulo || `Visita #${aviso.numero} - ${aviso.cliente}`,
      prioridad: aviso.urgencia === 'URGENTE' ? 'URGENTE' : aviso.urgencia === 'ALTA' ? 'ALTA' : prev.prioridad,
    }));
    setAvisoResults([]);
    setAvisoQuery(aviso.cliente);
  };

  const [showEmailPrompt, setShowEmailPrompt] = useState(false);
  const [pendingEventId, setPendingEventId] = useState<string | null>(null);

  const handleAutoFix = async () => {
    if (form.tecnicoIds.length === 0 || !form.fecha) return;
    const durationMin = form.horaInicio && form.horaFin
      ? timeToMinutes(form.horaFin) - timeToMinutes(form.horaInicio)
      : 60;
    const slot = await calculateSuggestedSlot(form.fecha, form.tecnicoIds[0], false, durationMin);
    if (slot) {
      setForm(prev => ({ ...prev, horaInicio: slot.horaInicio, horaFin: slot.horaFin }));
      setSolapWarning(null);
      setSolapFixSlot(null);
    }
  };

  const handleSubmit = async (isForcedEmail: boolean | any = false) => {
    const forcedEmail = typeof isForcedEmail === 'boolean' ? isForcedEmail : false;
    setError('');
    setSolapWarning(null);
    setSolapFixSlot(null);
    if (!form.titulo.trim()) { setError('Título obligatorio'); return; }
    if (!form.fecha) { setError('Fecha obligatoria'); return; }

    setLoading(true);
    try {
      const payload = {
        ...form,
        duracionMinutos: form.duracionMinutos ? parseInt(form.duracionMinutos) : null,
        horaInicio: form.todoElDia ? null : form.horaInicio,
        horaFin: form.todoElDia ? null : form.horaFin,
        fijado: form.fijado, // Added fijado to payload
        forzarEmail: forcedEmail,
      };
      const res = await fetch('/api/agenda', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();

      if (res.status === 409 && data.warning === 'solapamiento') {
        setSolapWarning(data.message);
        // Auto-calculate the fix slot
        if (form.tecnicoIds.length > 0) {
          const durationMin = form.horaInicio && form.horaFin
            ? timeToMinutes(form.horaFin) - timeToMinutes(form.horaInicio)
            : 60;
          const fixSlot = await calculateSuggestedSlot(form.fecha, form.tecnicoIds[0], false, durationMin);
          if (fixSlot) setSolapFixSlot({ horaInicio: fixSlot.horaInicio, horaFin: fixSlot.horaFin });
        }
        setLoading(false);
        return;
      }
      if (!res.ok) { setError(data.error || 'Error al crear'); setLoading(false); return; }

      if (data.promptEmail && !forcedEmail) {
        if (data.evento?.id) setPendingEventId(data.evento.id);
        setShowEmailPrompt(true);
        setLoading(false);
        return;
      }

      onCreated();
    } catch (err: any) {
      console.error('Submit error:', err);
      setError('Error interno: ' + (err?.message || 'Revisa la consola'));
    } finally {
      setLoading(false);
    }
  };

  const handleSendEmail = async () => {
    if (!pendingEventId) { onCreated(); return; }
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`/api/agenda/${pendingEventId}/email`, { method: 'POST' });
      const currentData = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(currentData.error || 'Error al enviar email');
        setLoading(false);
        return;
      }
      onCreated();
    } catch (e) {
      console.error('Error sending email', e);
      setError('Error de conexión al enviar correo');
      setLoading(false);
    }
  };

  if (showEmailPrompt) {
    return (
      <div className="fixed inset-0 bg-black/50 z-[60] flex items-center justify-center p-4">
        <div className="bg-white rounded-xl shadow-xl w-full max-w-sm p-6 space-y-4">
          <div className="flex items-center gap-3 text-[#1a365d]">
            <Info className="w-6 h-6" />
            <h3 className="text-lg font-bold">Enviar notificación</h3>
          </div>
          <p className="text-sm text-gray-600">
            ¿Desea enviar una notificación por correo electrónico al cliente con los detalles de la cita?
          </p>
          {error && (
            <div className="bg-red-50 text-red-700 p-2 rounded text-sm flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 flex-shrink-0" /> {error}
            </div>
          )}
          <div className="flex justify-end gap-3 pt-2">
            <button onClick={() => onCreated()} disabled={loading} className="px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 rounded-lg disabled:opacity-50">
              No enviar
            </button>
            <button onClick={handleSendEmail} disabled={loading} className="px-4 py-2 text-sm bg-[#1a365d] text-white rounded-lg hover:bg-[#2c5282] flex items-center gap-2 disabled:opacity-50">
              {loading && <Loader2 className="w-4 h-4 animate-spin" />}
              Enviar ahora
            </button>
          </div>
        </div>
      </div>
    );
  }

  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-xl max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-6 py-4 border-b bg-gray-50 rounded-t-xl sticky top-0 z-10">
          <div className="flex items-center gap-3">
            <h2 className="text-lg font-bold text-gray-900">Nuevo Evento</h2>
          </div>
          <div className="flex items-center gap-3">
            <button onClick={onClose} className="px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-200 rounded-lg transition-colors">Cancelar</button>
            <button onClick={handleSubmit} disabled={loading}
              className="flex items-center gap-2 px-3 py-1.5 text-sm bg-[#1a365d] hover:bg-[#2c5282] text-white rounded-lg font-medium disabled:opacity-60 transition-colors">
              {loading && <Loader2 className="w-4 h-4 animate-spin" />}
              Crear Evento
            </button>
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600 ml-2"><X className="w-5 h-5" /></button>
          </div>
        </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>
          )}
          {solapWarning && (
            <div className="bg-amber-50 border border-amber-200 p-3 rounded-lg text-sm text-amber-800">
              <div className="flex items-start gap-2">
                <AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
                <div className="flex-1">
                  <p className="font-medium">{solapWarning}</p>
                  {solapFixSlot ? (
                    <div className="mt-2 flex items-center gap-2">
                      <span className="text-xs">Horario libre: <strong>{solapFixSlot.horaInicio} - {solapFixSlot.horaFin}</strong></span>
                      <button
                        onClick={handleAutoFix}
                        className="px-2.5 py-1 text-xs font-medium bg-amber-600 text-white rounded-md hover:bg-amber-700 transition-colors"
                      >
                        Ajustar horario
                      </button>
                    </div>
                  ) : (
                    <p className="mt-1 text-xs">Ajusta el horario manualmente para evitar el solapamiento.</p>
                  )}
                </div>
              </div>
            </div>
          )}

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

          {/* Título */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Título *</label>
            <input type="text" value={form.titulo}
              onChange={e => setForm({ ...form, titulo: e.target.value })}
              placeholder="Descripción breve del evento"
              className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900 outline-none focus:ring-2 focus:ring-[#3182ce]"
            />
          </div>

          {/* Vincular aviso */}
          {(form.tipo === 'VISITA_AVISO' || selectedAviso) && (
            <div className="relative">
              <label className="block text-sm font-medium text-gray-700 mb-1">Vincular a aviso (opcional)</label>
              {selectedAviso ? (
                <div className="bg-blue-50 text-blue-700 p-2.5 rounded-lg text-sm flex items-center justify-between">
                  <div>
                    <span className="font-medium">Aviso #{selectedAviso.numero}</span> - {selectedAviso.cliente}
                    <p className="text-xs text-blue-500 mt-0.5 truncate">{selectedAviso.descripcion}</p>
                  </div>
                  <button onClick={() => { setSelectedAviso(null); setForm(p => ({ ...p, avisoId: '', parteId: '' })); setAvisoQuery(''); }}
                    className="ml-2 text-blue-400 hover:text-blue-700 flex-shrink-0"><X className="w-4 h-4" /></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={avisoQuery}
                      onChange={e => { setAvisoQuery(e.target.value); searchAvisos(e.target.value); }}
                      placeholder="Buscar aviso por cliente o descripción..."
                      className="w-full pl-9 pr-3 py-2 border rounded-lg text-sm text-gray-900 outline-none focus:ring-2 focus:ring-[#3182ce]"
                    />
                    {searchingAvisos && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-gray-400" />}
                  </div>
                  {avisoResults.length > 0 && (
                    <div className="absolute z-50 w-full mt-1 bg-white border rounded-lg shadow-lg max-h-40 overflow-y-auto">
                      {avisoResults.map(a => (
                        <button key={a.id} onClick={() => handleSelectAviso(a)}
                          className="w-full text-left px-3 py-2 hover:bg-blue-50 text-sm border-b last:border-0">
                          <span className="font-medium">#{a.numero}</span> {a.cliente}
                          <span className="text-xs text-gray-400 ml-2">{a.estado}</span>
                          <p className="text-xs text-gray-500 truncate">{a.descripcion}</p>
                        </button>
                      ))}
                    </div>
                  )}
                </>
              )}
              {/* Selector de parte si hay aviso */}
              {selectedAviso && selectedAviso.partes && selectedAviso.partes.length > 0 && (
                <div className="mt-2">
                  <label className="block text-xs text-gray-500 mb-1">Parte específico (opcional)</label>
                  <select value={form.parteId} onChange={e => setForm({ ...form, parteId: e.target.value })}
                    className="w-full px-3 py-1.5 border rounded-lg text-sm bg-white text-gray-900">
                    <option value="">-- Sin parte específico --</option>
                    {selectedAviso.partes.map(p => (
                      <option key={p.id} value={p.id}>Parte #{p.numero} - {p.descripcion}</option>
                    ))}
                  </select>
                </div>
              )}
            </div>
          )}

          {/* Fecha y hora */}
          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Fecha *</label>
              <input type="date" value={form.fecha}
                onChange={e => setForm({ ...form, fecha: e.target.value })}
                className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900"
              />
            </div>
            {!form.todoElDia && (
              <>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Hora inicio</label>
                  <input type="time" value={form.horaInicio}
                    onChange={e => setForm({ ...form, horaInicio: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Hora fin</label>
                  <input type="time" value={form.horaFin}
                    onChange={e => setForm({ ...form, horaFin: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900"
                  />
                </div>
              </>
            )}
          </div>

          {/* Suggested time slot - applied automatically, shown as info */}
          {!form.todoElDia && suggestedSlot && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
              <div className="flex items-start gap-2">
                <Info className="w-4 h-4 text-blue-500 mt-0.5 flex-shrink-0" />
                <div className="flex-1">
                  <p className="text-sm font-medium text-blue-800">Horario ajustado automáticamente</p>
                  <p className="text-xs text-blue-600 mt-0.5">
                    Última cita termina a las <span className="font-semibold">{suggestedSlot.previousEnd}</span>
                    {suggestedSlot.travelMinutes > 0 && (
                      <> + <Car className="w-3 h-3 inline" /> {suggestedSlot.travelMinutes}min traslado</>
                    )}
                    {' '}+ {suggestedSlot.marginMinutes}min margen →{' '}
                    <span className="font-semibold text-blue-800">
                      <Clock className="w-3 h-3 inline" /> {suggestedSlot.horaInicio} - {suggestedSlot.horaFin}
                    </span>
                  </p>
                </div>
              </div>
            </div>
          )}
          {calculatingSlot && (
            <div className="flex items-center gap-2 text-xs text-gray-400">
              <Loader2 className="w-3 h-3 animate-spin" /> Calculando horario sugerido...
            </div>
          )}

          {/* Opciones booleanas */}
          <div className="grid grid-cols-2 gap-4">
            <div className="mt-4 flex items-center gap-2 bg-gray-50 border border-gray-200 p-3 rounded-lg flex-1">
              <input type="checkbox" id="todoElDia" checked={form.todoElDia}
                onChange={e => {
                  setForm({ ...form, todoElDia: e.target.checked });
                  if (e.target.checked) setSuggestedSlot(null);
                }}
                className="w-4 h-4 text-[#1a365d] rounded"
              />
              <label htmlFor="todoElDia" className="text-sm font-medium text-gray-700 select-none cursor-pointer">Todo el día</label>
            </div>

            <div className="mt-4 flex items-center gap-2 bg-amber-50 border border-amber-200 p-3 rounded-lg flex-1">
              <input type="checkbox" id="fijado" checked={form.fijado}
                onChange={e => setForm({ ...form, fijado: e.target.checked })}
                className="w-4 h-4 text-amber-600 rounded"
              />
              <label htmlFor="fijado" className="text-sm font-medium text-amber-800 select-none cursor-pointer flex items-center gap-1" title="Si se marca, el sistema automático no podrá alterar o empujar este horario de cita.">
                Cita Inamovible (Fija)
                <Info className="w-3.5 h-3.5 text-amber-600 ml-1" />
              </label>
            </div>
          </div>
          {!form.todoElDia && (
            <div className="flex items-center gap-2">
              <label className="text-sm text-gray-500">Duración (min):</label>
              <input type="number" value={form.duracionMinutos}
                onChange={e => setForm({ ...form, duracionMinutos: e.target.value })}
                placeholder="60" className="w-20 px-2 py-1 border rounded text-sm text-gray-900"
              />
            </div>
          )}
        </div>

        {/* Técnicos */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Técnicos asignados {form.tecnicoIds.length > 0 && `(${form.tecnicoIds.length})`}
          </label>
          <div className="flex flex-wrap gap-2">
            {tecnicos.map(t => {
              const selected = form.tecnicoIds.includes(t.id);
              const idx = form.tecnicoIds.indexOf(t.id);
              return (
                <button key={t.id} onClick={() => handleToggleTecnico(t.id)}
                  className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${selected
                    ? 'bg-[#1a365d] text-white border-[#1a365d]'
                    : 'bg-white text-gray-600 border-gray-300 hover:border-[#3182ce]'
                    }`}>
                  {t.name || t.id}
                  {selected && idx === 0 && ' (Principal)'}
                  {selected && idx > 0 && ' (Apoyo)'}
                </button>
              );
            })}
          </div>
          {form.tecnicoIds.length > 1 && (
            <p className="text-xs text-gray-400 mt-1">El primer técnico seleccionado es el principal, los demás son apoyo.</p>
          )}
        </div>

        {/* Notas */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Notas</label>
          <textarea value={form.notas} onChange={e => setForm({ ...form, notas: e.target.value })}
            placeholder="Notas internas..." rows={2}
            className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900 resize-none outline-none focus:ring-2 focus:ring-[#3182ce]"
          />
        </div>

      </motion.div>
    </motion.div>
  );
}
