'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import {
  X, Clock, User, Phone, MessageCircle, Mail, Plus, Send, ChevronDown, ChevronUp,
  AlertTriangle, CheckCircle, Flag, RefreshCw, Loader2, Edit2, Trash2, History, DollarSign
} from 'lucide-react';
import {
  ESTADO_LABELS, ESTADO_COLORS, URGENCIA_LABELS, URGENCIA_COLORS,
  CANAL_LABELS, ESTADO_PARTE_LABELS, TRANSICIONES_VALIDAS
} from '@/lib/avisos/constants';
import { useRouter } from 'next/navigation';

interface Aviso {
  id: string;
  numero: number;
  estado: string;
  cliente: string;
  contacto: string | null;
  telefono: string | null;
  canal: string;
  urgencia: string;
  descripcion: string;
  presupuestoPendiente: boolean;
  fechaEntrada: string;
  fechaCierre: string | null;
  reabierto: boolean;
  vecesReabierto: number;
  creadoPor: { id: string; name: string; email: string } | null;
  asignadoA: { id: string; name: string; email: string } | null;
  partes: Parte[];
  presupuestos: { id: string; estado: string; facturado: boolean }[];
  notas: Nota[];
  historial: Historial[];
}

interface Parte {
  id: string;
  numero: number;
  descripcion: string;
  estado: string;
  tecnico: { id: string; name: string; email: string } | null;
  fechaProgramada: string | null;
  fechaInicio: string | null;
  fechaFin: string | null;
  observaciones: string | null;
  facturado: boolean;
  requierePresupuesto: boolean;
}

interface Nota {
  id: string;
  contenido: string;
  interna: boolean;
  createdAt: string;
  autor: { id: string; name: string } | null;
}

interface Historial {
  id: string;
  accion: string;
  estadoAnterior: string | null;
  estadoNuevo: string | null;
  detalles: string | null;
  createdAt: string;
  usuario: { id: string; name: string } | null;
}

interface Props {
  avisoId: string;
  userRole?: string;
  userId?: string;
  onClose: () => void;
}

export default function AvisoDetailModal({ avisoId, userRole = 'admin', userId = '', onClose }: Props) {
  const [aviso, setAviso] = useState<Aviso | null>(null);
  const [loading, setLoading] = useState(true);
  const [usuarios, setUsuarios] = useState<{ id: string; name: string; email: string; role?: string }[]>([]);
  const [activeTab, setActiveTab] = useState<'partes' | 'notas' | 'historial'>('partes');
  const [showNuevaParte, setShowNuevaParte] = useState(false);
  const [nuevaNota, setNuevaNota] = useState('');
  const [nuevaParte, setNuevaParte] = useState({ descripcion: '', tecnicoId: '', fechaProgramada: '', observaciones: '' });
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [showCierreModal, setShowCierreModal] = useState(false);
  const [notaCierre, setNotaCierre] = useState('');

  // Operario: aplazar y presupuesto
  const [showAplazarModal, setShowAplazarModal] = useState(false);
  const [aplazarFecha, setAplazarFecha] = useState('');
  const [aplazarTipo, setAplazarTipo] = useState<'manana' | 'otro'>('manana');
  const [showPresupuestoModal, setShowPresupuestoModal] = useState(false);
  const [notasPresupuestoInput, setNotasPresupuestoInput] = useState('');
  const [showFacturarAvisoModal, setShowFacturarAvisoModal] = useState(false);

  const isOperario = userRole === 'operario';
  const canEdit = userRole === 'admin' || userRole === 'oficina';
  const router = useRouter();

  const fetchAviso = useCallback(async () => {
    try {
      const res = await fetch(`/api/avisos/${avisoId}`);
      const data = await res.json();
      if (data.aviso) setAviso(data.aviso);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [avisoId]);

  useEffect(() => {
    fetchAviso();
    // Fetch users for assignment dropdown
    fetch('/api/users')
      .then(r => r.json())
      .then(data => {
        // Correct handler for { success: true, users: [...] } format
        if (data.users && Array.isArray(data.users)) {
          setUsuarios(data.users);
        } else if (Array.isArray(data)) {
          setUsuarios(data);
        }
      })
      .catch(() => { });
  }, [fetchAviso]);

  const showMsg = (type: 'success' | 'error', text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 3000);
  };

  const handleChangeEstado = async (nuevoEstado: string) => {
    // Si intenta cerrar, abrir modal de cierre con notas
    if (nuevoEstado === 'CERRADO') {
      setShowCierreModal(true);
      return;
    }
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ estado: nuevoEstado }),
      });
      const data = await res.json();
      if (!res.ok) {
        showMsg('error', data.error);
      } else {
        showMsg('success', `Estado cambiado a ${ESTADO_LABELS[nuevoEstado]}`);
        fetchAviso();
      }
    } catch { showMsg('error', 'Error de conexión'); }
    finally { setSaving(false); }
  };

  const handleCerrarAviso = async () => {
    setSaving(true);
    try {
      // 1. Si hay nota de cierre, guardarla primero
      if (notaCierre.trim()) {
        await fetch(`/api/avisos/${avisoId}/notas`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ contenido: `[CIERRE] ${notaCierre}`, interna: true }),
        });
      }

      // 2. Cambiar estado a CERRADO
      const res = await fetch(`/api/avisos/${avisoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ estado: 'CERRADO' }),
      });
      const data = await res.json();
      if (!res.ok) {
        showMsg('error', data.error);
      } else {
        showMsg('success', 'Aviso cerrado correctamente');
        setShowCierreModal(false);
        setNotaCierre('');
        fetchAviso();
      }
    } catch { showMsg('error', 'Error de conexión'); }
    finally { setSaving(false); }
  };

  const handleAsignar = async (userId: string) => {
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ asignadoAId: userId || null }),
      });
      if (res.ok) {
        showMsg('success', userId ? 'Técnico asignado' : 'Técnico desasignado');
        fetchAviso();
      }
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  const handleTogglePresupuesto = async () => {
    if (!aviso) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ presupuestoPendiente: !aviso.presupuestoPendiente }),
      });
      if (res.ok) {
        fetchAviso();
      }
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  const handleReabrir = async () => {
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}/reabrir`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ motivo: 'Cliente llamó de nuevo por el mismo problema' }),
      });
      if (res.ok) {
        showMsg('success', 'Aviso reabierto');
        fetchAviso();
      }
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  const handleAddNota = async () => {
    if (!nuevaNota.trim()) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}/notas`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contenido: nuevaNota, interna: true }),
      });
      if (res.ok) {
        setNuevaNota('');
        fetchAviso();
      }
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  const handleAddParte = async () => {
    if (!nuevaParte.descripcion.trim()) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}/partes`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          descripcion: nuevaParte.descripcion,
          tecnicoId: nuevaParte.tecnicoId || null,
          fechaProgramada: nuevaParte.fechaProgramada || null,
          observaciones: nuevaParte.observaciones || null,
        }),
      });
      if (res.ok) {
        setNuevaParte({ descripcion: '', tecnicoId: '', fechaProgramada: '', observaciones: '' });
        setShowNuevaParte(false);
        fetchAviso();
      }
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  const handleUpdateParte = async (parteId: string, estado: string) => {
    setSaving(true);
    try {
      await fetch(`/api/partes/${parteId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ estado }),
      });
      fetchAviso();
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  // Operario: auto-asignarse
  const handleAutoAsignar = async () => {
    if (!userId) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ asignadoAId: userId }),
      });
      if (res.ok) {
        showMsg('success', 'Te has asignado este aviso');
        fetchAviso();
      }
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  // Operario: aplazar aviso
  const handleAplazar = async () => {
    let fecha: string;
    if (aplazarTipo === 'manana') {
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      fecha = tomorrow.toISOString().split('T')[0];
    } else {
      if (!aplazarFecha) { showMsg('error', 'Selecciona una fecha'); return; }
      fecha = aplazarFecha;
    }

    setSaving(true);
    try {
      // Add note about postponement
      await fetch(`/api/avisos/${avisoId}/notas`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contenido: `[APLAZADO] Aviso aplazado al ${new Date(fecha).toLocaleDateString('es-ES')}`,
          interna: true,
        }),
      });

      // Move associated agenda events to the new date
      showMsg('success', `Aviso aplazado al ${new Date(fecha).toLocaleDateString('es-ES')}`);
      setShowAplazarModal(false);
      fetchAviso();
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  // Operario: solicitar presupuesto
  const handleSolicitarPresupuesto = async () => {
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ presupuestoPendiente: true }),
      });
      if (res.ok && notasPresupuestoInput.trim()) {
        await fetch(`/api/avisos/${avisoId}/notas`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            contenido: `[PRESUPUESTO] ${notasPresupuestoInput}`,
            interna: true,
          }),
        });
      }
      showMsg('success', 'Presupuesto solicitado');
      setShowPresupuestoModal(false);
      setNotasPresupuestoInput('');
      fetchAviso();
    } catch { showMsg('error', 'Error'); }
    finally { setSaving(false); }
  };

  const handleFacturarAviso = async () => {
    setSaving(true);
    try {
      const res = await fetch(`/api/avisos/${avisoId}/facturar`, {
        method: 'POST',
      });
      const data = await res.json();
      if (!res.ok) {
        showMsg('error', data.error || 'Error al facturar el aviso');
      } else {
        router.push(`/dashboard/facturas/${data.facturaId}`);
        onClose(); // Cerrar el modal para forzar purga de cache
      }
    } catch {
      showMsg('error', 'Fallo de conexión al generar la factura');
    } finally {
      setSaving(false);
      setShowFacturarAvisoModal(false);
    }
  };

  const formatDate = (d: string) =>
    new Date(d).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' });

  if (loading) {
    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">
        <div className="bg-white rounded-xl p-8"><Loader2 className="w-8 h-8 animate-spin text-[#1a365d]" /></div>
      </motion.div>
    );
  }

  if (!aviso) return null;

  const transicionesDisponibles = TRANSICIONES_VALIDAS[aviso.estado] || [];

  const partesFacturablesPendientes = aviso?.partes?.filter(p => !p.facturado && p.estado !== 'CANCELADO' && !p.requierePresupuesto) || [];
  const presupuestosPendientes = aviso?.presupuestos?.filter(p => !p.facturado && p.estado === 'ACEPTADO') || [];
  const puedeFacturarse = partesFacturablesPendientes.length > 0 || presupuestosPendientes.length > 0;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 z-50 flex items-end md:items-center justify-center"
      onClick={onClose}
    >
      <motion.div
        initial={{ y: 50, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        exit={{ y: 50, opacity: 0 }}
        className="bg-white rounded-t-xl md:rounded-xl shadow-xl w-full max-w-3xl max-h-[92vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="sticky top-0 bg-white border-b px-6 py-4 z-10 rounded-t-xl">
          <div className="flex items-start justify-between">
            <div>
              <div className="flex items-center gap-3">
                <span className="text-sm font-mono text-gray-500">Aviso #{aviso.numero}</span>
                <span className={`text-xs px-2 py-1 rounded-full font-medium ${ESTADO_COLORS[aviso.estado]}`}>
                  {ESTADO_LABELS[aviso.estado]}
                </span>
                <span className={`text-xs px-2 py-1 rounded font-medium ${URGENCIA_COLORS[aviso.urgencia]}`}>
                  {URGENCIA_LABELS[aviso.urgencia]}
                </span>
                {aviso.reabierto && (
                  <span className="text-xs bg-orange-100 text-orange-700 px-2 py-1 rounded">
                    <RefreshCw className="w-3 h-3 inline" /> Reabierto {aviso.vecesReabierto}x
                  </span>
                )}
              </div>
              <h2 className="text-lg font-bold text-gray-900 mt-1">{aviso.cliente}</h2>
            </div>
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X className="w-5 h-5" /></button>
          </div>

          {message && (
            <div className={`mt-3 p-2 rounded-lg text-sm flex items-center gap-2 ${message.type === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'
              }`}>
              {message.type === 'success' ? <CheckCircle className="w-4 h-4" /> : <AlertTriangle className="w-4 h-4" />}
              {message.text}
            </div>
          )}
        </div>

        <div className="p-6 space-y-6">
          {/* Info */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <span className="text-gray-500 block text-xs mb-0.5">Contacto</span>
              <span className="font-medium text-gray-900">{aviso.contacto || '-'}</span>
            </div>
            <div>
              <span className="text-gray-500 block text-xs mb-0.5">Teléfono</span>
              <span className="font-medium text-gray-900">{aviso.telefono || '-'}</span>
            </div>
            <div>
              <span className="text-gray-500 block text-xs mb-0.5">Canal</span>
              <span className="font-medium text-gray-900">{CANAL_LABELS[aviso.canal]}</span>
            </div>
            <div>
              <span className="text-gray-500 block text-xs mb-0.5">Entrada</span>
              <span className="font-medium text-gray-900">{formatDate(aviso.fechaEntrada)}</span>
            </div>
            {aviso.asignadoA && (
              <div>
                <span className="text-gray-500 block text-xs mb-0.5">Técnico asignado</span>
                <span className="font-medium text-gray-900 flex items-center gap-1">
                  <User className="w-3 h-3 text-blue-500" /> {aviso.asignadoA.name}
                </span>
              </div>
            )}
            {aviso.fechaCierre && (
              <div>
                <span className="text-gray-500 block text-xs mb-0.5">Fecha de cierre</span>
                <span className="font-medium text-green-700 flex items-center gap-1">
                  <CheckCircle className="w-3 h-3" /> {formatDate(aviso.fechaCierre)}
                </span>
              </div>
            )}
          </div>

          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="text-xs font-medium text-gray-500 mb-1">Descripción</h4>
            <p className="text-sm text-gray-900 whitespace-pre-wrap">{aviso.descripcion}</p>
          </div>

          {/* Actions bar */}
          <div className="flex flex-wrap gap-2">
            {/* Operario: auto-asignarse */}
            {isOperario && !aviso.asignadoA && aviso.estado !== 'CERRADO' && aviso.estado !== 'CANCELADO' && (
              <button
                onClick={handleAutoAsignar}
                disabled={saving}
                className="text-xs px-3 py-1.5 rounded-lg font-medium border border-blue-300 text-blue-700 hover:bg-blue-50 disabled:opacity-50"
              >
                <User className="w-3 h-3 inline mr-1" /> Asignarme este aviso
              </button>
            )}

            {/* Admin/Oficina: Asignar técnico */}
            {!isOperario && (
              <select
                value={aviso.asignadoA?.id || ''}
                onChange={(e) => handleAsignar(e.target.value)}
                disabled={saving || aviso.estado === 'CERRADO' || aviso.estado === 'CANCELADO'}
                className="text-sm border border-gray-300 rounded-lg px-3 py-1.5 bg-white text-gray-700 disabled:opacity-50"
              >
                <option value="">Sin asignar</option>
                {usuarios
                  .filter(u => u.role === 'operario' || u.role === 'admin' || u.role === 'oficina')
                  .map((u) => (
                    <option key={u.id} value={u.id}>{u.name || u.email}</option>
                  ))}
              </select>
            )}

            {/* Transiciones */}
            {transicionesDisponibles.map((est) => (
              <button
                key={est}
                onClick={() => handleChangeEstado(est)}
                disabled={saving}
                className={`text-xs px-3 py-1.5 rounded-lg font-medium transition-colors border ${est === 'CANCELADO'
                  ? 'border-red-300 text-red-700 hover:bg-red-50'
                  : est === 'CERRADO'
                    ? 'border-green-300 text-green-700 hover:bg-green-50'
                    : 'border-gray-300 text-gray-700 hover:bg-gray-50'
                  } disabled:opacity-50`}
              >
                {'→'} {ESTADO_LABELS[est]}
              </button>
            ))}

            {/* Reabrir */}
            {aviso.estado === 'CERRADO' && !isOperario && (
              <button
                onClick={handleReabrir}
                disabled={saving}
                className="text-xs px-3 py-1.5 rounded-lg font-medium border border-orange-300 text-orange-700 hover:bg-orange-50 disabled:opacity-50"
              >
                <RefreshCw className="w-3 h-3 inline mr-1" /> Reabrir
              </button>
            )}

            {/* Admin/Oficina: Facturar Aviso Completo */}
            {canEdit && puedeFacturarse && (
              <button
                onClick={() => setShowFacturarAvisoModal(true)}
                disabled={saving}
                className="text-xs px-3 py-1.5 rounded-lg font-medium border border-blue-600 bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 transition-colors shadow-sm"
              >
                <DollarSign className="w-3 h-3 inline mr-1" /> Facturar Aviso General
              </button>
            )}

            {/* Presupuesto flag - Admin/Oficina toggle directo */}
            {!isOperario && (
              <button
                onClick={handleTogglePresupuesto}
                disabled={saving}
                className={`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors disabled:opacity-50 ${aviso.presupuestoPendiente
                  ? 'border-amber-400 bg-amber-50 text-amber-700'
                  : 'border-gray-300 text-gray-600 hover:bg-gray-50'
                  }`}
              >
                <Flag className="w-3 h-3 inline mr-1" />
                {aviso.presupuestoPendiente ? 'Presup. pendiente ✓' : 'Marcar presup. pdte.'}
              </button>
            )}

            {/* Operario: Solicitar presupuesto con notas */}
            {isOperario && !aviso.presupuestoPendiente && aviso.estado !== 'CERRADO' && aviso.estado !== 'CANCELADO' && (
              <button
                onClick={() => setShowPresupuestoModal(true)}
                disabled={saving}
                className="text-xs px-3 py-1.5 rounded-lg font-medium border border-amber-300 text-amber-700 hover:bg-amber-50 disabled:opacity-50"
              >
                <Flag className="w-3 h-3 inline mr-1" /> Solicitar presupuesto
              </button>
            )}
            {isOperario && aviso.presupuestoPendiente && (
              <span className="text-xs px-3 py-1.5 rounded-lg font-medium border border-amber-400 bg-amber-50 text-amber-700">
                <Flag className="w-3 h-3 inline mr-1" /> Presup. pendiente ✓
              </span>
            )}

            {/* Operario: Aplazar */}
            {isOperario && aviso.estado !== 'CERRADO' && aviso.estado !== 'CANCELADO' && (
              <button
                onClick={() => setShowAplazarModal(true)}
                disabled={saving}
                className="text-xs px-3 py-1.5 rounded-lg font-medium border border-gray-300 text-gray-700 hover:bg-gray-50 disabled:opacity-50"
              >
                <Clock className="w-3 h-3 inline mr-1" /> Aplazar
              </button>
            )}
          </div>

          {/* Tabs */}
          <div className="border-b">
            <div className="flex gap-6">
              {(['partes', 'notas', 'historial'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`pb-2 text-sm font-medium border-b-2 transition-colors capitalize ${activeTab === tab
                    ? 'border-[#1a365d] text-[#1a365d]'
                    : 'border-transparent text-gray-500 hover:text-gray-700'
                    }`}
                >
                  {tab === 'partes' ? `Partes (${aviso.partes.length})` : tab === 'notas' ? `Notas (${aviso.notas.length})` : 'Historial'}
                </button>
              ))}
            </div>
          </div>

          {/* Tab Content */}
          {activeTab === 'partes' && (
            <div className="space-y-3">
              {aviso.estado !== 'CERRADO' && aviso.estado !== 'CANCELADO' && (
                <button
                  onClick={() => {
                    if (!showNuevaParte && aviso.asignadoA?.id && !nuevaParte.tecnicoId) {
                      setNuevaParte(prev => ({ ...prev, tecnicoId: aviso.asignadoA!.id }));
                    }
                    setShowNuevaParte(!showNuevaParte);
                  }}
                  className="flex items-center gap-1.5 text-sm text-[#3182ce] hover:text-[#2c5282] font-medium"
                >
                  <Plus className="w-4 h-4" /> Añadir parte
                </button>
              )}

              {showNuevaParte && (
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-3">
                  <input
                    type="text"
                    placeholder="Descripción de la parte *"
                    value={nuevaParte.descripcion}
                    onChange={(e) => setNuevaParte({ ...nuevaParte, descripcion: e.target.value })}
                    className="w-full px-3 py-2 border rounded-lg text-sm text-gray-900"
                  />
                  <div className="grid grid-cols-2 gap-3">
                    <select
                      value={nuevaParte.tecnicoId}
                      onChange={(e) => setNuevaParte({ ...nuevaParte, tecnicoId: e.target.value })}
                      className="px-3 py-2 border rounded-lg text-sm bg-white text-gray-700"
                    >
                      <option value="">Técnico (opcional)</option>
                      {usuarios
                        .filter(u => u.role === 'operario' || u.role === 'admin' || u.role === 'oficina')
                        .map((u) => <option key={u.id} value={u.id}>{u.name || u.email}</option>)}
                    </select>
                    <input
                      type="datetime-local"
                      value={nuevaParte.fechaProgramada}
                      onChange={(e) => setNuevaParte({ ...nuevaParte, fechaProgramada: e.target.value })}
                      className="px-3 py-2 border rounded-lg text-sm text-gray-700"
                    />
                  </div>
                  <textarea
                    placeholder="Observaciones (opcional)"
                    value={nuevaParte.observaciones}
                    onChange={(e) => setNuevaParte({ ...nuevaParte, observaciones: e.target.value })}
                    rows={2}
                    className="w-full px-3 py-2 border rounded-lg text-sm resize-none text-gray-900"
                  />
                  <div className="flex gap-2">
                    <button onClick={handleAddParte} disabled={saving} className="text-sm bg-[#1a365d] text-white px-4 py-1.5 rounded-lg hover:bg-[#2c5282] disabled:opacity-60">
                      Crear Parte
                    </button>
                    <button onClick={() => {
                      setShowNuevaParte(false);
                      setNuevaParte({ descripcion: '', tecnicoId: '', fechaProgramada: '', observaciones: '' });
                    }} className="text-sm text-gray-600 px-4 py-1.5 rounded-lg hover:bg-gray-100">
                      Cancelar
                    </button>
                  </div>
                </div>
              )}

              {aviso.partes.length === 0 ? (
                <p className="text-sm text-gray-400 py-4 text-center">Sin partes asociadas</p>
              ) : (
                aviso.partes.map((parte) => (
                  <div key={parte.id} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex items-start justify-between">
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-xs font-mono text-gray-500">Parte #{parte.numero}</span>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${parte.estado === 'FINALIZADO' ? 'bg-green-100 text-green-700' :
                            parte.estado === 'EN_PROCESO' ? 'bg-purple-100 text-purple-700' :
                              parte.estado === 'CANCELADO' ? 'bg-gray-100 text-gray-700' :
                                'bg-yellow-100 text-yellow-700'
                            }`}>
                            {ESTADO_PARTE_LABELS[parte.estado]}
                          </span>
                        </div>
                        <p className="text-sm text-gray-900">{parte.descripcion}</p>
                        {parte.tecnico && (
                          <p className="text-xs text-gray-500 mt-1">
                            <User className="w-3 h-3 inline" /> {parte.tecnico.name}
                          </p>
                        )}
                        {parte.fechaProgramada && (
                          <p className="text-xs text-gray-500 mt-0.5">
                            <Clock className="w-3 h-3 inline" /> Programada: {formatDate(parte.fechaProgramada)}
                          </p>
                        )}
                        {parte.observaciones && (
                          <p className="text-xs text-gray-500 mt-1 italic">{parte.observaciones}</p>
                        )}
                      </div>
                      <div className="flex flex-col gap-1">
                        {parte.estado === 'PENDIENTE' && (
                          <button onClick={() => handleUpdateParte(parte.id, 'EN_PROCESO')} className="text-xs px-2 py-1 bg-purple-100 text-purple-700 rounded hover:bg-purple-200">Iniciar</button>
                        )}
                        {parte.estado === 'EN_PROCESO' && (
                          <button onClick={() => handleUpdateParte(parte.id, 'FINALIZADO')} className="text-xs px-2 py-1 bg-green-100 text-green-700 rounded hover:bg-green-200">Finalizar</button>
                        )}
                        {(parte.estado === 'PENDIENTE' || parte.estado === 'EN_PROCESO') && (
                          <button onClick={() => handleUpdateParte(parte.id, 'CANCELADO')} className="text-xs px-2 py-1 bg-gray-100 text-gray-600 rounded hover:bg-gray-200">Cancelar</button>
                        )}
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}

          {activeTab === 'notas' && (
            <div className="space-y-3">
              <div className="flex gap-2">
                <input
                  type="text"
                  placeholder="Escribir nota interna..."
                  value={nuevaNota}
                  onChange={(e) => setNuevaNota(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleAddNota()}
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900"
                />
                <button
                  onClick={handleAddNota}
                  disabled={saving || !nuevaNota.trim()}
                  className="px-3 py-2 bg-[#1a365d] text-white rounded-lg hover:bg-[#2c5282] disabled:opacity-50"
                >
                  <Send className="w-4 h-4" />
                </button>
              </div>

              {aviso.notas.length === 0 ? (
                <p className="text-sm text-gray-400 py-4 text-center">Sin notas</p>
              ) : (
                aviso.notas.map((nota) => (
                  <div key={nota.id} className="bg-gray-50 rounded-lg p-3">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs font-medium text-gray-700">{nota.autor?.name || 'Sistema'}</span>
                      <span className="text-xs text-gray-400">{formatDate(nota.createdAt)}</span>
                    </div>
                    <p className="text-sm text-gray-800">{nota.contenido}</p>
                  </div>
                ))
              )}
            </div>
          )}

          {activeTab === 'historial' && (
            <div className="space-y-2">
              {aviso.historial.length === 0 ? (
                <p className="text-sm text-gray-400 py-4 text-center">Sin historial</p>
              ) : (
                aviso.historial.map((h) => (
                  <div key={h.id} className="flex items-start gap-3 py-2 border-b border-gray-50">
                    <div className="w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center flex-shrink-0 mt-0.5">
                      <History className="w-3 h-3 text-gray-500" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm text-gray-800">{h.detalles || h.accion}</p>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-xs text-gray-500">{h.usuario?.name || 'Sistema'}</span>
                        <span className="text-xs text-gray-400">{formatDate(h.createdAt)}</span>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}
        </div>

        {/* Modal de cierre con notas */}
        {showCierreModal && (
          <div className="fixed inset-0 bg-black/40 z-[60] flex items-center justify-center" onClick={() => setShowCierreModal(false)}>
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 p-6" onClick={(e) => e.stopPropagation()}>
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                  <CheckCircle className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">Cerrar Aviso #{aviso.numero}</h3>
                  <p className="text-sm text-gray-500">A{'ñ'}ade notas sobre la resoluci{'ó'}n</p>
                </div>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Notas de cierre <span className="text-gray-400">(opcional)</span>
                </label>
                <textarea
                  value={notaCierre}
                  onChange={(e) => setNotaCierre(e.target.value)}
                  placeholder="Describe lo que se hizo, solución aplicada, observaciones..."
                  rows={4}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 focus:border-transparent outline-none resize-none text-gray-900"
                  autoFocus
                />
              </div>

              <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 mb-4 text-sm text-amber-700">
                Se registrar{'á'} la fecha de cierre actual y el aviso pasar{'á'} a estado &quot;Cerrado&quot;.
                {aviso.partes.some(p => p.estado !== 'FINALIZADO' && p.estado !== 'CANCELADO') && (
                  <span className="block mt-1 font-medium text-red-600">
                    {'⚠'} Hay partes sin finalizar. Deben estar finalizadas o canceladas para cerrar.
                  </span>
                )}
              </div>

              <div className="flex gap-3 justify-end">
                <button
                  onClick={() => { setShowCierreModal(false); setNotaCierre(''); }}
                  className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  Cancelar
                </button>
                <button
                  onClick={handleCerrarAviso}
                  disabled={saving}
                  className="px-4 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors font-medium"
                >
                  {saving ? 'Cerrando...' : 'Confirmar cierre'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Modal aplazar aviso */}
        {showAplazarModal && (
          <div className="fixed inset-0 bg-black/40 z-[60] flex items-center justify-center" onClick={() => setShowAplazarModal(false)}>
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-sm mx-4 p-6" onClick={(e) => e.stopPropagation()}>
              <h3 className="text-lg font-bold text-gray-900 mb-4">Aplazar Aviso #{aviso.numero}</h3>

              <div className="space-y-3 mb-4">
                <label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
                  <input
                    type="radio"
                    name="aplazarTipo"
                    checked={aplazarTipo === 'manana'}
                    onChange={() => setAplazarTipo('manana')}
                    className="text-blue-600"
                  />
                  Aplazar a ma{'ñ'}ana
                </label>
                <label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
                  <input
                    type="radio"
                    name="aplazarTipo"
                    checked={aplazarTipo === 'otro'}
                    onChange={() => setAplazarTipo('otro')}
                    className="text-blue-600"
                  />
                  Aplazar a otro d{'í'}a
                </label>
                {aplazarTipo === 'otro' && (
                  <input
                    type="date"
                    value={aplazarFecha}
                    onChange={(e) => setAplazarFecha(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900"
                  />
                )}
              </div>

              <div className="flex gap-3 justify-end">
                <button onClick={() => setShowAplazarModal(false)} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg">Cancelar</button>
                <button onClick={handleAplazar} disabled={saving}
                  className="px-4 py-2 text-sm bg-[#1a365d] text-white rounded-lg hover:bg-[#2c5282] disabled:opacity-50 font-medium">
                  {saving ? 'Aplazando...' : 'Confirmar'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Modal solicitar presupuesto */}
        {showPresupuestoModal && (
          <div className="fixed inset-0 bg-black/40 z-[60] flex items-center justify-center" onClick={() => setShowPresupuestoModal(false)}>
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 p-6" onClick={(e) => e.stopPropagation()}>
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-full bg-amber-100 flex items-center justify-center">
                  <Flag className="w-5 h-5 text-amber-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">Solicitar Presupuesto</h3>
                  <p className="text-sm text-gray-500">Aviso #{aviso.numero} - {aviso.cliente}</p>
                </div>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Notas para la empresa <span className="text-gray-400">(directrices, piezas, acciones...)</span>
                </label>
                <textarea
                  value={notasPresupuestoInput}
                  onChange={(e) => setNotasPresupuestoInput(e.target.value)}
                  placeholder="Indicar piezas necesarias, acciones a realizar, directrices principales..."
                  rows={4}
                  className="w-full px-3 py-2 border border-amber-300 bg-amber-50 rounded-lg text-sm focus:ring-2 focus:ring-amber-500 focus:border-transparent outline-none resize-none text-gray-900"
                  autoFocus
                />
              </div>

              <div className="flex gap-3 justify-end">
                <button onClick={() => { setShowPresupuestoModal(false); setNotasPresupuestoInput(''); }}
                  className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg">Cancelar</button>
                <button onClick={handleSolicitarPresupuesto} disabled={saving}
                  className="px-4 py-2 text-sm bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 font-medium">
                  {saving ? 'Enviando...' : 'Solicitar presupuesto'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Modal Confirmación de Facturación General */}
        {showFacturarAvisoModal && (
          <div className="fixed inset-0 bg-black/40 z-[60] flex items-center justify-center p-4" onClick={() => setShowFacturarAvisoModal(false)}>
            <div className="bg-white rounded-xl shadow-2xl w-full max-w-md p-6" onClick={(e) => e.stopPropagation()}>
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center shrink-0">
                  <DollarSign className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">Agrupar en Factura</h3>
                  <p className="text-sm text-gray-500">Aviso #{aviso.numero} - {aviso.cliente}</p>
                </div>
              </div>

              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                <p className="text-sm text-blue-800 mb-2">Se procederá a generar una <b>única factura</b> consolidando los siguientes conceptos listos de este aviso:</p>
                <ul className="list-disc pl-5 text-sm text-blue-700 space-y-1">
                  <li><strong>Partes pendientes:</strong> {partesFacturablesPendientes.length}</li>
                  <li><strong>Presupuestos aprobados:</strong> {presupuestosPendientes.length}</li>
                </ul>
                <p className="text-xs text-blue-600 mt-3">Al confirmar, serás redirigido automáticamente a la nueva factura para revisarla y descargarla en PDF.</p>
              </div>

              <div className="flex gap-3 justify-end">
                <button
                  onClick={() => setShowFacturarAvisoModal(false)}
                  disabled={saving}
                  className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  Cancelar
                </button>
                <button
                  onClick={handleFacturarAviso}
                  disabled={saving}
                  className="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors font-medium"
                >
                  {saving ? 'Generando Factura...' : 'Agrupar y Facturar'}
                </button>
              </div>
            </div>
          </div>
        )}

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