'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  X, Loader2, Clock, User, ClipboardList, Calendar, Trash2,
  CheckCircle2, Play, XCircle, RotateCcw, Phone, MapPin,
  MessageSquare, Send, Building2, Info, Lock,
} from 'lucide-react';
import {
  TIPO_EVENTO_LABELS, TIPO_EVENTO_COLORS, ESTADO_EVENTO_LABELS, ESTADO_EVENTO_COLORS,
  PRIORIDAD_LABELS, PRIORIDAD_COLORS, ROL_ASIGNACION_LABELS, TRANSICIONES_EVENTO,
} from '@/lib/agenda/constants';

interface Props {
  eventoId: string;
  tecnicos: { id: string; name: string }[];
  userRole: string;
  onClose: () => void;
  onUpdated: () => void;
}

export default function EventoDetailModal({ eventoId, tecnicos, userRole, onClose, onUpdated }: Props) {
  const [evento, setEvento] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [editMode, setEditMode] = useState(false);
  const [editForm, setEditForm] = useState<any>({});
  const [activeTab, setActiveTab] = useState<'detalle' | 'aviso' | 'notas'>('detalle');

  // Notes state
  const [eventNote, setEventNote] = useState('');
  const [avisoNote, setAvisoNote] = useState('');
  const [savingNote, setSavingNote] = useState(false);
  const [avisoDetails, setAvisoDetails] = useState<any>(null);
  const [loadingAviso, setLoadingAviso] = useState(false);

  useEffect(() => {
    fetchEvento();
  }, [eventoId]);

  const fetchEvento = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/agenda/${eventoId}`);
      if (res.ok) {
        const data = await res.json();
        setEvento(data);
        setEditForm({
          titulo: data.titulo,
          tipo: data.tipo,
          fecha: data.fecha?.split('T')[0],
          horaInicio: data.horaInicio || '',
          horaFin: data.horaFin || '',
          duracionMinutos: data.duracionMinutos || '',
          todoElDia: data.todoElDia,
          fijado: data.fijado || false,
          notas: data.notas || '',
          prioridad: data.prioridad,
          tecnicoIds: data.asignaciones?.map((a: any) => a.tecnicoId) || [],
        });
        // Fetch aviso details if linked
        if (data.avisoId) {
          fetchAvisoDetails(data.avisoId);
        }
      }
    } catch { setError('Error cargando evento'); }
    setLoading(false);
  };

  const fetchAvisoDetails = async (avisoId: string) => {
    setLoadingAviso(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}`);
      if (res.ok) {
        const data = await res.json();
        setAvisoDetails(data.aviso || data);
      }
    } catch { /* ignore */ }
    setLoadingAviso(false);
  };

  const handleEstadoChange = async (nuevoEstado: string) => {
    setSaving(true);
    setError('');
    try {
      const res = await fetch(`/api/agenda/${eventoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ estado: nuevoEstado }),
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error || 'Error');
      } else {
        onUpdated();
      }
    } catch { setError('Error de conexión'); }
    setSaving(false);
  };

  const [showEmailPrompt, setShowEmailPrompt] = useState(false);

  const handleSaveEdit = async (isForcedEmail = false) => {
    setSaving(true);
    setError('');
    try {
      const res = await fetch(`/api/agenda/${eventoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...editForm,
          horaInicio: editForm.todoElDia ? null : editForm.horaInicio,
          horaFin: editForm.todoElDia ? null : editForm.horaFin,
          duracionMinutos: editForm.todoElDia ? null : (parseInt(editForm.duracionMinutos) || null),
          fijado: editForm.fijado,
          tecnicoIds: editForm.tecnicoIds,
          forzarSolapamiento: true,
          forzarEmail: isForcedEmail,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Error al guardar');
      } else {
        if (data.promptEmail && !isForcedEmail) {
          setShowEmailPrompt(true);
          setSaving(false);
          return;
        }
        onUpdated();
      }
    } catch { setError('Error de conexión'); }
    setSaving(false);
  };

  const handleSaveEventNote = async () => {
    if (!eventNote.trim()) return;
    setSavingNote(true);
    try {
      const currentNotas = evento?.notas || '';
      const timestamp = new Date().toLocaleString('es-ES');
      const newNotas = currentNotas
        ? `${currentNotas}\n\n[${timestamp}] ${eventNote.trim()}`
        : `[${timestamp}] ${eventNote.trim()}`;
      const res = await fetch(`/api/agenda/${eventoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ notas: newNotas }),
      });
      if (res.ok) {
        setEventNote('');
        fetchEvento();
      }
    } catch { /* ignore */ }
    setSavingNote(false);
  };

  const handleSaveAvisoNote = async () => {
    if (!avisoNote.trim() || !evento?.avisoId) return;
    setSavingNote(true);
    try {
      const res = await fetch(`/api/avisos/${evento.avisoId}/notas`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contenido: avisoNote.trim() }),
      });
      if (res.ok) {
        setAvisoNote('');
        fetchAvisoDetails(evento.avisoId);
      }
    } catch { /* ignore */ }
    setSavingNote(false);
  };

  const handleDelete = async () => {
    if (!confirm('¿Eliminar este evento?')) return;
    try {
      const res = await fetch(`/api/agenda/${eventoId}`, { method: 'DELETE' });
      if (res.ok) onUpdated();
      else {
        const data = await res.json();
        setError(data.error || 'Error al eliminar');
      }
    } catch { setError('Error'); }
  };

  const estadoActions = (estado: string) => {
    const transitions = TRANSICIONES_EVENTO[estado] || [];
    return transitions.map(t => {
      let icon = <Play className="w-3.5 h-3.5" />;
      let color = 'bg-gray-100 text-gray-700 hover:bg-gray-200';
      if (t === 'EN_CURSO') { icon = <Play className="w-3.5 h-3.5" />; color = 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200'; }
      if (t === 'COMPLETADO') { icon = <CheckCircle2 className="w-3.5 h-3.5" />; color = 'bg-green-100 text-green-700 hover:bg-green-200'; }
      if (t === 'CANCELADO') { icon = <XCircle className="w-3.5 h-3.5" />; color = 'bg-red-100 text-red-700 hover:bg-red-200'; }
      if (t === 'PLANIFICADO') { icon = <RotateCcw className="w-3.5 h-3.5" />; color = 'bg-blue-100 text-blue-700 hover:bg-blue-200'; }
      return { estado: t, icon, color, label: ESTADO_EVENTO_LABELS[t] };
    });
  };

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

  const tabs = [
    { key: 'detalle' as const, label: 'Detalle' },
    ...(evento?.avisoId ? [{ key: 'aviso' as const, label: 'Aviso' }] : []),
    { key: 'notas' as const, label: 'Notas' },
  ];

  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 bg-white rounded-t-xl sticky top-0 z-10 shadow-sm">
          <h2 className="text-lg font-bold text-gray-900">
            {editMode ? 'Editar Evento' : 'Detalle del Evento'}
          </h2>
          <div className="flex items-center gap-3">
            {editMode ? (
              <>
                <button onClick={() => setEditMode(false)} className="px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded-lg">Cancelar</button>
                <button onClick={() => handleSaveEdit()} disabled={saving}
                  className="flex items-center gap-2 px-3 py-1.5 text-sm bg-[#1a365d] text-white rounded-lg font-medium disabled:opacity-60">
                  {saving && <Loader2 className="w-4 h-4 animate-spin" />} Guardar
                </button>
              </>
            ) : (
              !loading && evento && (
                <>
                  <button onClick={() => setEditMode(true)} className="px-3 py-1.5 text-sm bg-blue-50 text-[#3182ce] hover:bg-blue-100 rounded-lg font-medium transition-colors">
                    ✏ Editar
                  </button>
                </>
              )
            )}
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600 ml-2"><X className="w-5 h-5" /></button>
          </div>
        </div>

        {loading ? (
          <div className="p-12 flex justify-center"><Loader2 className="w-6 h-6 animate-spin text-gray-400" /></div>
        ) : !evento ? (
          <div className="p-12 text-center text-gray-500">Evento no encontrado</div>
        ) : editMode ? (
          /* EDIT MODE */
          <div className="p-6 space-y-4">
            {error && <div className="bg-red-50 text-red-700 p-2 rounded text-sm">{error}</div>}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Título</label>
              <input type="text" value={editForm.titulo}
                onChange={e => setEditForm({ ...editForm, titulo: e.target.value })}
                className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
                <select value={editForm.tipo} onChange={e => setEditForm({ ...editForm, 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={editForm.prioridad} onChange={e => setEditForm({ ...editForm, 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>
            <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={editForm.fecha}
                  onChange={e => setEditForm({ ...editForm, fecha: e.target.value })}
                  className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900" />
              </div>
              {!editForm.todoElDia && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Inicio</label>
                    <input type="time" value={editForm.horaInicio}
                      onChange={e => setEditForm({ ...editForm, 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">Fin</label>
                    <input type="time" value={editForm.horaFin}
                      onChange={e => setEditForm({ ...editForm, horaFin: e.target.value })}
                      className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900" />
                  </div>
                </>
              )}
            </div>
            {/* Opciones booleanas */}
            <div className="grid grid-cols-2 gap-4 mt-4">
              <div className="flex items-center gap-2 bg-gray-50 border border-gray-200 p-3 rounded-lg flex-1">
                <input type="checkbox" id="todoElDiaEdit" checked={editForm.todoElDia}
                  onChange={e => setEditForm({ ...editForm, todoElDia: e.target.checked })}
                  className="w-4 h-4 text-[#1a365d] rounded"
                />
                <label htmlFor="todoElDiaEdit" className="text-sm font-medium text-gray-700 select-none cursor-pointer">Todo el día</label>
              </div>

              <div className="flex items-center gap-2 bg-amber-50 border border-amber-200 p-3 rounded-lg flex-1">
                <input type="checkbox" id="fijadoEdit" checked={editForm.fijado}
                  onChange={e => setEditForm({ ...editForm, fijado: e.target.checked })}
                  className="w-4 h-4 text-amber-600 rounded"
                />
                <label htmlFor="fijadoEdit" className="text-sm font-medium text-amber-800 select-none cursor-pointer flex items-center gap-1">
                  <Lock className="w-3.5 h-3.5" /> Cita Inamovible
                </label>
              </div>
            </div>

            {userRole !== 'operario' && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Técnicos</label>
                <div className="flex flex-wrap gap-2">
                  {tecnicos.map(t => {
                    const sel = editForm.tecnicoIds.includes(t.id);
                    const idx = editForm.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 ${sel ? 'bg-[#1a365d] text-white border-[#1a365d]' : 'bg-white text-gray-600 border-gray-300 hover:border-[#3182ce]'
                          }`}>
                        {t.name}{sel && idx === 0 ? ' (Principal)' : sel ? ' (Apoyo)' : ''}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Notas</label>
              <textarea value={editForm.notas} onChange={e => setEditForm({ ...editForm, notas: e.target.value })}
                rows={3} className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900 resize-none" />
            </div>
          </div>
        ) : (
          /* VIEW MODE with tabs */
          <div>
            {/* Tabs */}
            <div className="flex border-b px-6">
              {tabs.map(tab => (
                <button
                  key={tab.key}
                  onClick={() => setActiveTab(tab.key)}
                  className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${activeTab === tab.key
                    ? 'border-[#1a365d] text-[#1a365d]'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                    }`}
                >
                  {tab.label}
                </button>
              ))}
            </div>

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

              {activeTab === 'detalle' && (
                <>
                  {/* Header */}
                  <div>
                    <h3 className="text-xl font-bold text-gray-900">{evento.titulo}</h3>
                    <div className="flex items-center gap-2 mt-1 flex-wrap">
                      <span className={`text-xs px-2 py-0.5 rounded-full ${TIPO_EVENTO_COLORS[evento.tipo]}`}>
                        {TIPO_EVENTO_LABELS[evento.tipo]}
                      </span>
                      <span className={`text-xs px-2 py-0.5 rounded-full ${ESTADO_EVENTO_COLORS[evento.estado]}`}>
                        {ESTADO_EVENTO_LABELS[evento.estado]}
                      </span>
                      <span className={`text-xs ${PRIORIDAD_COLORS[evento.prioridad]}`}>
                        {PRIORIDAD_LABELS[evento.prioridad]}
                      </span>
                      {evento.fijado && (
                        <span className="text-xs px-2 py-0.5 rounded-full bg-amber-100 text-amber-800 flex items-center gap-1 border border-amber-200">
                          📌 Inamovible (Fija)
                        </span>
                      )}
                    </div>
                  </div>

                  {/* Fecha y hora */}
                  <div className="flex items-center gap-3 text-sm text-gray-700">
                    <Calendar className="w-4 h-4 text-gray-400" />
                    <span>{new Date(evento.fecha).toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</span>
                  </div>
                  {evento.horaInicio && (
                    <div className="flex items-center gap-3 text-sm text-gray-700">
                      <Clock className="w-4 h-4 text-gray-400" />
                      <span>{evento.horaInicio}{evento.horaFin ? ` - ${evento.horaFin}` : ''}</span>
                      {evento.duracionMinutos && <span className="text-gray-400">({evento.duracionMinutos} min)</span>}
                    </div>
                  )}
                  {evento.todoElDia && <div className="text-sm text-gray-500">Todo el día</div>}

                  {/* Técnicos */}
                  <div>
                    <h4 className="text-sm font-medium text-gray-700 mb-2">Técnicos asignados</h4>
                    {evento.asignaciones.length === 0 ? (
                      <p className="text-sm text-gray-400">Sin técnicos asignados</p>
                    ) : (
                      <div className="flex flex-wrap gap-2">
                        {evento.asignaciones.map((a: any) => (
                          <div key={a.id} className="flex items-center gap-1.5 bg-gray-100 rounded-full px-3 py-1">
                            <User className="w-3.5 h-3.5 text-gray-500" />
                            <span className="text-sm text-gray-800">{a.tecnico.name}</span>
                            <span className="text-[10px] text-gray-400">{ROL_ASIGNACION_LABELS[a.rol]}</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>

                  {/* Aviso vinculado */}
                  {evento.aviso && (
                    <div className="bg-blue-50 rounded-lg p-3">
                      <div className="flex items-center gap-2 text-sm font-medium text-blue-800">
                        <ClipboardList className="w-4 h-4" />
                        Aviso #{evento.aviso.numero} - {evento.aviso.cliente}
                      </div>
                      <p className="text-xs text-blue-600 mt-1">Estado: {evento.aviso.estado} | Urgencia: {evento.aviso.urgencia}</p>
                      {evento.aviso.descripcion && (
                        <p className="text-xs text-blue-500 mt-1">{evento.aviso.descripcion}</p>
                      )}
                    </div>
                  )}

                  {/* Notas resumen */}
                  {evento.notas && (
                    <div className="text-sm text-gray-600 bg-gray-50 rounded-lg p-3">
                      <span className="font-medium">Notas:</span>
                      <pre className="whitespace-pre-wrap text-xs mt-1 font-sans">{evento.notas}</pre>
                    </div>
                  )}

                  {/* Acciones de estado */}
                  <div className="flex flex-wrap gap-2 pt-2">
                    {estadoActions(evento.estado).map(action => (
                      <button key={action.estado} onClick={() => handleEstadoChange(action.estado)} disabled={saving}
                        className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${action.color}`}>
                        {action.icon} {action.label}
                      </button>
                    ))}
                  </div>

                  {/* Botones eliminar */}
                  <div className="flex items-center justify-end pt-3 border-t">
                    {userRole === 'admin' && (
                      <button onClick={handleDelete}
                        className="flex items-center gap-1 text-sm text-red-500 hover:text-red-700 bg-red-50 px-3 py-1.5 rounded-lg transition-colors">
                        <Trash2 className="w-4 h-4" /> Eliminar Evento
                      </button>
                    )}
                  </div>
                </>
              )}

              {activeTab === 'aviso' && evento.avisoId && (
                <div className="space-y-4">
                  {loadingAviso ? (
                    <div className="flex justify-center py-6"><Loader2 className="w-5 h-5 animate-spin text-gray-400" /></div>
                  ) : avisoDetails ? (
                    <>
                      {/* Client info */}
                      <div className="bg-gray-50 rounded-lg p-4 space-y-2">
                        <div className="flex items-center gap-2">
                          <Building2 className="w-4 h-4 text-gray-400" />
                          <span className="text-sm font-semibold text-gray-900">{avisoDetails.cliente}</span>
                        </div>
                        {avisoDetails.contacto && (
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <User className="w-3.5 h-3.5 text-gray-400" />
                            <span>{avisoDetails.contacto}</span>
                          </div>
                        )}
                        {avisoDetails.telefono && (
                          <div className="flex items-center gap-2 text-sm text-gray-600">
                            <Phone className="w-3.5 h-3.5 text-gray-400" />
                            <a href={`tel:${avisoDetails.telefono}`} className="text-blue-600 hover:underline">{avisoDetails.telefono}</a>
                          </div>
                        )}
                        {avisoDetails.clienteRef && avisoDetails.clienteRef.direcciones && avisoDetails.clienteRef.direcciones.length > 0 && (
                          <div className="flex items-start gap-2 text-sm text-gray-600">
                            <MapPin className="w-3.5 h-3.5 text-gray-400 mt-0.5" />
                            <span>{avisoDetails.clienteRef.direcciones[0].calle}{avisoDetails.clienteRef.direcciones[0].ciudad ? `, ${avisoDetails.clienteRef.direcciones[0].ciudad}` : ''}</span>
                          </div>
                        )}
                      </div>

                      {/* Aviso description */}
                      <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-1">Descripción del aviso</h4>
                        <p className="text-sm text-gray-600 bg-white border rounded-lg p-3">{avisoDetails.descripcion}</p>
                      </div>

                      {/* Aviso state */}
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-gray-500">Estado del aviso:</span>
                        <span className="text-xs font-medium bg-gray-100 px-2 py-0.5 rounded">{avisoDetails.estado}</span>
                      </div>

                      {/* Aviso notes */}
                      <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-1.5">
                          <MessageSquare className="w-4 h-4" /> Notas del aviso
                        </h4>
                        {avisoDetails.notas && avisoDetails.notas.length > 0 ? (
                          <div className="space-y-2 max-h-40 overflow-y-auto">
                            {avisoDetails.notas.map((nota: any) => (
                              <div key={nota.id} className="bg-gray-50 rounded-lg p-2.5 text-sm">
                                <p className="text-gray-700">{nota.contenido}</p>
                                <p className="text-[10px] text-gray-400 mt-1">
                                  {nota.autor?.name || 'Desconocido'} - {new Date(nota.createdAt).toLocaleString('es-ES')}
                                </p>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <p className="text-xs text-gray-400">Sin notas todavía</p>
                        )}
                        <div className="flex gap-2 mt-2">
                          <input
                            type="text"
                            value={avisoNote}
                            onChange={e => setAvisoNote(e.target.value)}
                            placeholder="Añadir nota al aviso..."
                            className="flex-1 px-3 py-1.5 border rounded-lg text-sm text-gray-900 outline-none focus:ring-1 focus:ring-[#3182ce]"
                            onKeyDown={e => e.key === 'Enter' && handleSaveAvisoNote()}
                          />
                          <button onClick={handleSaveAvisoNote} disabled={savingNote || !avisoNote.trim()}
                            className="px-3 py-1.5 bg-[#1a365d] text-white rounded-lg text-sm disabled:opacity-50">
                            {savingNote ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                          </button>
                        </div>
                      </div>
                    </>
                  ) : (
                    <p className="text-sm text-gray-400">No se pudo cargar la información del aviso</p>
                  )}
                </div>
              )}

              {activeTab === 'notas' && (
                <div className="space-y-4">
                  <h4 className="text-sm font-medium text-gray-700">Notas del evento</h4>
                  {evento.notas ? (
                    <div className="bg-gray-50 rounded-lg p-3">
                      <pre className="whitespace-pre-wrap text-sm text-gray-700 font-sans">{evento.notas}</pre>
                    </div>
                  ) : (
                    <p className="text-xs text-gray-400">Sin notas todavía</p>
                  )}
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={eventNote}
                      onChange={e => setEventNote(e.target.value)}
                      placeholder="Añadir nota al evento..."
                      className="flex-1 px-3 py-1.5 border rounded-lg text-sm text-gray-900 outline-none focus:ring-1 focus:ring-[#3182ce]"
                      onKeyDown={e => e.key === 'Enter' && handleSaveEventNote()}
                    />
                    <button onClick={handleSaveEventNote} disabled={savingNote || !eventNote.trim()}
                      className="px-3 py-1.5 bg-[#1a365d] text-white rounded-lg text-sm disabled:opacity-50">
                      {savingNote ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </motion.div>

      {/* Pop-up de confirmación de email para edición manual */}
      {showEmailPrompt && (
        <div className="fixed inset-0 bg-black/50 z-[100] 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 el nuevo horario?
            </p>
            <div className="flex justify-end gap-3 pt-2">
              <button
                onClick={() => onUpdated()}
                className="px-4 py-2 text-sm text-gray-500 hover:bg-gray-100 rounded-lg"
              >
                No enviar
              </button>
              <button
                onClick={() => {
                  handleSaveEdit(true);
                  setShowEmailPrompt(false);
                }}
                className="px-4 py-2 text-sm bg-[#1a365d] text-white rounded-lg hover:bg-[#2c5282]"
              >
                Enviar ahora
              </button>
            </div>
          </div>
        </div>
      )}
    </motion.div>
  );
}
