'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { motion } from 'framer-motion';
import {
  X, Plus, Trash2, Loader2, AlertTriangle, Wrench, Clock, Search, Info,
  Paperclip, Upload, ImageIcon, FileText, CheckCircle
} from 'lucide-react';
import { TIPO_PARTE_LABELS, UNIDADES } from '@/lib/partes/constants';
import { calcularHoras } from '@/lib/partes/calculo-horas';

interface Props {
  onClose: () => void;
  onCreated: () => void;
  avisoPreseleccionado?: { id: string; numero: number; cliente: string; clienteId?: string; asignadoAId?: string } | null;
  userRole?: string;
  userId?: string;
}

interface AvisoOption {
  id: string;
  numero: number;
  cliente: string;
  clienteId?: string | null;
  descripcion: string;
  estado: string;
  urgencia?: string;
  asignadoA?: { id: string; name: string } | null;
}

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

interface MaterialForm {
  descripcion: string;
  cantidad: string;
  unidad: string;
  precioUnit: string;
}

export default function NuevoParteModal({ onClose, onCreated, avisoPreseleccionado, userRole, userId }: Props) {
  // --- Modo de selección: 'aviso' (buscar aviso) o 'cliente' (buscar cliente → elegir aviso) ---
  const [modoSeleccion, setModoSeleccion] = useState<'aviso' | 'cliente'>('aviso');

  // Aviso seleccionado (fuente de verdad)
  const [avisoSeleccionado, setAvisoSeleccionado] = useState<AvisoOption | null>(null);
  const [avisoSearch, setAvisoSearch] = useState('');
  const [avisoResults, setAvisoResults] = useState<AvisoOption[]>([]);
  const [showAvisoDropdown, setShowAvisoDropdown] = useState(false);
  const [searchingAvisos, setSearchingAvisos] = useState(false);

  // Cliente seleccionado (para modo 'cliente')
  const [clienteSeleccionado, setClienteSeleccionado] = useState<ClienteOption | null>(null);
  const [clienteSearch, setClienteSearch] = useState('');
  const [clienteResults, setClienteResults] = useState<ClienteOption[]>([]);
  const [showClienteDropdown, setShowClienteDropdown] = useState(false);
  const [searchingClientes, setSearchingClientes] = useState(false);

  // Avisos abiertos del cliente seleccionado (modo 'cliente')
  const [avisosDelCliente, setAvisosDelCliente] = useState<AvisoOption[]>([]);
  const [loadingAvisosCliente, setLoadingAvisosCliente] = useState(false);

  // Campos del parte
  const [tipo, setTipo] = useState('AVISO_REPARACION');
  const [descripcion, setDescripcion] = useState('');

  // Técnicos
  const [usuarios, setUsuarios] = useState<{ id: string; name: string; email: string; role: string }[]>([]);
  const [tecnicoIds, setTecnicoIds] = useState<{ tecnicoId: string; rol: string }[]>([]);

  // Fecha/hora
  const [fechaInicio, setFechaInicio] = useState('');
  const [horaInicio, setHoraInicio] = useState('');
  const [horaFin, setHoraFin] = useState('');
  const [descontarComida, setDescontarComida] = useState(true);
  const [horasCalculadasPreview, setHorasCalculadasPreview] = useState<string | null>(null);

  // Facturación
  const [facturable, setFacturable] = useState(true);
  const [importeEstimado, setImporteEstimado] = useState('');

  // Presupuesto
  const [requierePresupuesto, setRequierePresupuesto] = useState(false);
  const [notasPresupuesto, setNotasPresupuesto] = useState('');

  // Materiales
  const [materiales, setMateriales] = useState<MaterialForm[]>([]);

  const [observaciones, setObservaciones] = useState('');

  // Adjuntos
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [uploadProgress, setUploadProgress] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const avisoSearchTimeout = useRef<NodeJS.Timeout | null>(null);
  const clienteSearchTimeout = useRef<NodeJS.Timeout | null>(null);

  // Init: fecha de hoy (client-side)
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
    setFechaInicio(new Date().toISOString().split('T')[0]);
  }, []);

  // Avisos iniciales
  const [avisosIniciales, setAvisosIniciales] = useState<AvisoOption[]>([]);
  const [loadingAvisosIniciales, setLoadingAvisosIniciales] = useState(false);

  // Cargar usuarios
  useEffect(() => {
    fetch('/api/users').then(r => r.json()).then(data => {
      if (Array.isArray(data)) setUsuarios(data);
      else if (data?.users) setUsuarios(data.users);
    }).catch(() => { });
  }, []);

  // Cargar avisos iniciales (propios si es operario, o todos los abiertos si es admin)
  useEffect(() => {
    setLoadingAvisosIniciales(true);
    let url = `/api/avisos?estado=PENDIENTE,ASIGNADO,EN_PROCESO&limit=50`;
    if (userRole === 'operario' && userId) {
      url += `&asignadoAId=${userId}`;
    }
    fetch(url)
      .then(r => r.json())
      .then(data => {
        if (data.avisos) {
          setAvisosIniciales(data.avisos.map((a: AvisoOption & { asignadoA?: { id: string; name: string } | null }) => ({
            id: a.id, numero: a.numero, cliente: a.cliente, descripcion: a.descripcion,
            clienteId: a.clienteId || null, estado: a.estado,
            asignadoA: a.asignadoA || null,
          })));
        }
      })
      .catch(() => { })
      .finally(() => setLoadingAvisosIniciales(false));
  }, [userRole, userId]);

  // Auto-fill desde avisoPreseleccionado
  useEffect(() => {
    if (avisoPreseleccionado) {
      setAvisoSeleccionado({
        id: avisoPreseleccionado.id,
        numero: avisoPreseleccionado.numero,
        cliente: avisoPreseleccionado.cliente,
        clienteId: avisoPreseleccionado.clienteId || null,
        descripcion: '',
        estado: '',
      });
      // Cargar datos completos vía autofill
      fetch(`/api/partes/autofill?avisoId=${avisoPreseleccionado.id}`)
        .then(r => r.json())
        .then(data => {
          if (data.aviso) {
            setAvisoSeleccionado({
              id: data.aviso.id,
              numero: data.aviso.numero,
              cliente: data.aviso.cliente,
              clienteId: data.aviso.clienteId,
              descripcion: data.aviso.descripcion,
              estado: data.aviso.estado,
              urgencia: data.aviso.urgencia,
              asignadoA: data.aviso.asignadoA,
            });
            if (!descripcion) setDescripcion(data.aviso.descripcion || '');
            if (data.aviso.asignadoA?.id && tecnicoIds.length === 0) {
              setTecnicoIds([{ tecnicoId: data.aviso.asignadoA.id, rol: 'PRINCIPAL' }]);
            }
          }
        })
        .catch(() => { });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [avisoPreseleccionado]);

  // Calcular horas en tiempo real
  useEffect(() => {
    if (horaInicio && horaFin) {
      const resultado = calcularHoras({ horaInicio, horaFin, descontarComida });
      setHorasCalculadasPreview(resultado.detalle);
    } else {
      setHorasCalculadasPreview(null);
    }
  }, [horaInicio, horaFin, descontarComida]);

  // --- Búsqueda de avisos ---
  const searchAvisos = (q: string) => {
    if (avisoSearchTimeout.current) clearTimeout(avisoSearchTimeout.current);
    if (q.length < 2) { setAvisoResults([]); return; }
    setSearchingAvisos(true);
    avisoSearchTimeout.current = setTimeout(async () => {
      try {
        // Solo avisos no cerrados/cancelados
        const res = await fetch(`/api/avisos?q=${encodeURIComponent(q)}&estado=PENDIENTE,ASIGNADO,EN_PROCESO&limit=10`);
        const data = await res.json();
        if (data.avisos) {
          setAvisoResults(data.avisos.map((a: AvisoOption & { asignadoA?: { id: string; name: string } | null }) => ({
            id: a.id, numero: a.numero, cliente: a.cliente, descripcion: a.descripcion,
            clienteId: a.clienteId || null, estado: a.estado,
            asignadoA: a.asignadoA || null,
          })));
        }
      } catch { /* ignore */ }
      finally { setSearchingAvisos(false); }
    }, 300);
  };

  const handleSelectAviso = useCallback(async (aviso: AvisoOption) => {
    setShowAvisoDropdown(false);
    setAvisoSearch('');
    // Cargar datos completos vía autofill
    try {
      const res = await fetch(`/api/partes/autofill?avisoId=${aviso.id}`);
      const data = await res.json();
      if (data.aviso) {
        const a = data.aviso;
        setAvisoSeleccionado({
          id: a.id, numero: a.numero, cliente: a.cliente, clienteId: a.clienteId,
          descripcion: a.descripcion, estado: a.estado, urgencia: a.urgencia,
          asignadoA: a.asignadoA,
        });
        // Autofill campos
        if (!descripcion) setDescripcion(a.descripcion || '');
        if (a.asignadoA?.id && tecnicoIds.length === 0) {
          setTecnicoIds([{ tecnicoId: a.asignadoA.id, rol: 'PRINCIPAL' }]);
        }
      } else {
        setAvisoSeleccionado(aviso);
      }
    } catch {
      setAvisoSeleccionado(aviso);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [descripcion, tecnicoIds]);

  // --- Búsqueda de clientes ---
  const searchClientes = (q: string) => {
    if (clienteSearchTimeout.current) clearTimeout(clienteSearchTimeout.current);
    if (q.length < 2) { setClienteResults([]); return; }
    setSearchingClientes(true);
    clienteSearchTimeout.current = setTimeout(async () => {
      try {
        const res = await fetch(`/api/clientes/search?q=${encodeURIComponent(q)}`);
        const data = await res.json();
        if (data.clientes) setClienteResults(data.clientes);
      } catch { /* ignore */ }
      finally { setSearchingClientes(false); }
    }, 300);
  };

  const handleSelectCliente = async (cliente: ClienteOption) => {
    setClienteSeleccionado(cliente);
    setShowClienteDropdown(false);
    setClienteSearch('');
    // Cargar avisos abiertos de este cliente
    setLoadingAvisosCliente(true);
    try {
      const res = await fetch(`/api/partes/autofill?clienteId=${cliente.id}`);
      const data = await res.json();
      if (data.avisosAbiertos) {
        setAvisosDelCliente(data.avisosAbiertos);
        // Si solo hay 1 aviso, seleccionarlo automáticamente
        if (data.avisosAbiertos.length === 1) {
          handleSelectAviso(data.avisosAbiertos[0]);
        }
      } else {
        setAvisosDelCliente([]);
      }
    } catch {
      setAvisosDelCliente([]);
    } finally {
      setLoadingAvisosCliente(false);
    }
  };

  // --- Limpiar selección ---
  const clearAviso = () => {
    setAvisoSeleccionado(null);
    setAvisoSearch('');
    setAvisoResults([]);
  };

  const clearCliente = () => {
    setClienteSeleccionado(null);
    setClienteSearch('');
    setAvisosDelCliente([]);
    clearAviso();
  };

  // --- Técnicos ---
  const addTecnico = () => {
    setTecnicoIds([...tecnicoIds, { tecnicoId: '', rol: tecnicoIds.length === 0 ? 'PRINCIPAL' : 'APOYO' }]);
  };
  const removeTecnico = (idx: number) => setTecnicoIds(tecnicoIds.filter((_, i) => i !== idx));
  const updateTecnico = (idx: number, field: string, value: string) => {
    const updated = [...tecnicoIds];
    updated[idx] = { ...updated[idx], [field]: value };
    setTecnicoIds(updated);
  };

  // --- Materiales ---
  const addMaterial = () => {
    setMateriales([...materiales, { descripcion: '', cantidad: '1', unidad: 'ud', precioUnit: '' }]);
  };
  const removeMaterial = (idx: number) => setMateriales(materiales.filter((_, i) => i !== idx));
  const updateMaterial = (idx: number, field: string, value: string) => {
    const updated = [...materiales];
    updated[idx] = { ...updated[idx], [field]: value };
    setMateriales(updated);
  };

  // --- Archivos ---
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setSelectedFiles(prev => [...prev, ...Array.from(e.target.files as FileList)]);
    }
    // clear input to allow adding same file again if removed
    if (fileInputRef.current) fileInputRef.current.value = '';
  };
  const removeFile = (idx: number) => {
    setSelectedFiles(selectedFiles.filter((_, i) => i !== idx));
  };
  const isImageFile = (type: string) => type.startsWith('image/');

  // --- Submit ---
  const handleSubmit = async () => {
    if (!avisoSeleccionado) {
      setError('Debe seleccionar un aviso vinculado. Un parte no puede existir sin aviso.');
      return;
    }
    if (!descripcion.trim()) {
      setError('La descripción es obligatoria');
      return;
    }
    const validTecnicos = tecnicoIds.filter(t => t.tecnicoId);
    const validMateriales = materiales.filter(m => m.descripcion.trim());

    setSaving(true);
    setError('');
    try {
      const res = await fetch('/api/partes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          tipo,
          descripcion,
          avisoId: avisoSeleccionado.id,
          clienteId: avisoSeleccionado.clienteId || null,
          clienteNombre: avisoSeleccionado.cliente || null,
          tecnicoIds: validTecnicos,
          fechaInicio: fechaInicio || null,
          horaInicio: horaInicio || null,
          horaFin: horaFin || null,
          descontarComida,
          facturable,
          importeEstimado: importeEstimado || null,
          requierePresupuesto,
          notasPresupuesto: notasPresupuesto || null,
          observaciones: observaciones || null,
          materiales: validMateriales.map(m => ({
            descripcion: m.descripcion,
            cantidad: parseFloat(m.cantidad) || 1,
            unidad: m.unidad,
            precioUnit: m.precioUnit ? parseFloat(m.precioUnit) : null,
          })),
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        setError(data.error || 'Error al crear parte');
        setSaving(false);
        return;
      }

      const createdData = await res.json();
      const newParteId = createdData.parte?.id;

      // Subir archivos si existen
      if (newParteId && selectedFiles.length > 0) {
        // We do not set saving(false) yet because we are uploading
        for (let i = 0; i < selectedFiles.length; i++) {
          const file = selectedFiles[i];
          setUploadProgress(`Subiendo archivo ${i + 1}/${selectedFiles.length}: ${file.name}...`);
          try {
            const formData = new FormData();
            formData.append('file', file);

            const uploadRes = await fetch(`/api/partes/${newParteId}/adjuntos`, {
              method: 'POST',
              body: formData, // No Content-Type header needed for FormData (browser sets it with boundary)
            });

            if (!uploadRes.ok) {
              const eRes = await uploadRes.json();
              throw new Error(`Upload failed: ${eRes.error || uploadRes.statusText}`);
            }
          } catch (err: any) {
            console.error('Error subiendo archivo', file.name, err);
            setError(`Error subiendo ${file.name}: ${err.message}`);
            setSaving(false);
            return; // Detener la ejecución si hay error en la subida para poder leer el mensaje
          }
        }
      }

      onCreated();
    } catch {
      setError('Error de conexión');
      setSaving(false);
    }
    // Note: Do not `setSaving(false)` here if successful, to prevent double-clicks while modal closes, handled by onCreated/unmount
  };

  const tecnicosDisponibles = usuarios.filter(u => u.role === 'operario' || u.role === 'admin');

  if (!mounted) return null;

  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-2xl max-h-[92vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="sticky top-0 bg-white border-b px-6 py-4 z-10 rounded-t-xl">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="bg-blue-100 p-2 rounded-lg"><Wrench className="w-5 h-5 text-blue-700" /></div>
              <h2 className="text-lg font-bold text-gray-900">Nuevo Parte de Trabajo</h2>
            </div>
            <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X className="w-5 h-5" /></button>
          </div>
        </div>

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

          {/* ====== PASO 1: Selección de aviso (obligatorio) ====== */}
          {!avisoSeleccionado ? (
            <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 space-y-3">
              <div className="flex items-center gap-2 text-blue-800">
                <Info className="w-4 h-4" />
                <span className="text-sm font-medium">Paso 1: Seleccione el aviso vinculado (obligatorio)</span>
              </div>

              {/* MODO OPERARIO: lista directa de sus avisos */}
              {userRole === 'operario' ? (
                loadingAvisosIniciales ? (
                  <div className="flex items-center gap-2 text-sm text-gray-500 py-2">
                    <Loader2 className="w-4 h-4 animate-spin" /> Cargando tus avisos asignados...
                  </div>
                ) : avisosIniciales.length === 0 ? (
                  <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-800">
                    <AlertTriangle className="w-4 h-4 inline mr-1" />
                    No tienes avisos asignados en estado activo.
                  </div>
                ) : (
                  <div>
                    <p className="text-xs text-gray-600 mb-2 font-medium">Tus avisos asignados ({avisosIniciales.length}):</p>
                    <div className="space-y-1 max-h-52 overflow-y-auto">
                      {avisosIniciales.map((a) => (
                        <button
                          key={a.id}
                          type="button"
                          onClick={() => handleSelectAviso(a)}
                          className="w-full text-left px-3 py-2 rounded-lg hover:bg-blue-100 border border-gray-200 text-sm transition bg-white"
                        >
                          <div className="flex items-center gap-2">
                            <span className="font-mono text-blue-600 font-medium">#{a.numero}</span>
                            <span className="font-medium text-gray-900">{a.cliente}</span>
                            <span className={`text-xs px-1.5 py-0.5 rounded ${a.estado === 'PENDIENTE' ? 'bg-yellow-100 text-yellow-800' :
                              a.estado === 'ASIGNADO' ? 'bg-blue-100 text-blue-800' :
                                'bg-purple-100 text-purple-800'
                              }`}>{a.estado}</span>
                          </div>
                          <span className="text-gray-500 text-xs line-clamp-1">{a.descripcion}</span>
                        </button>
                      ))}
                    </div>
                  </div>
                )
              ) : (
                // MODO ADMIN: búsqueda libre + búsqueda por cliente
                <>
                  {/* Tabs: Buscar por aviso / Buscar por cliente */}
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={() => { setModoSeleccion('aviso'); clearCliente(); }}
                      className={`text-xs px-3 py-1.5 rounded-lg font-medium transition ${modoSeleccion === 'aviso'
                        ? 'bg-blue-600 text-white'
                        : 'bg-white text-blue-700 border border-blue-300 hover:bg-blue-100'
                        }`}
                    >
                      Buscar por aviso
                    </button>
                    <button
                      type="button"
                      onClick={() => { setModoSeleccion('cliente'); setAvisoResults([]); setAvisoSearch(''); }}
                      className={`text-xs px-3 py-1.5 rounded-lg font-medium transition ${modoSeleccion === 'cliente'
                        ? 'bg-blue-600 text-white'
                        : 'bg-white text-blue-700 border border-blue-300 hover:bg-blue-100'
                        }`}
                    >
                      Buscar por cliente
                    </button>
                  </div>

                  {/* Modo AVISO: búsqueda directa de avisos abiertos */}
                  {modoSeleccion === 'aviso' && (
                    <div className="relative">
                      <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={avisoSearch}
                          onChange={(e) => {
                            setAvisoSearch(e.target.value);
                            searchAvisos(e.target.value);
                            setShowAvisoDropdown(true);
                          }}
                          onFocus={() => avisoResults.length > 0 && setShowAvisoDropdown(true)}
                          onBlur={() => setTimeout(() => setShowAvisoDropdown(false), 200)}
                          placeholder="Buscar aviso por número, cliente o descripción..."
                          className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900 bg-white"
                        />
                        {searchingAvisos && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-gray-400" />}
                      </div>
                      {showAvisoDropdown && avisoResults.length > 0 && (
                        <div className="absolute z-20 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-56 overflow-y-auto">
                          {avisoResults.map((a) => (
                            <button
                              key={a.id}
                              type="button"
                              onMouseDown={(e) => e.preventDefault()}
                              onClick={() => handleSelectAviso(a)}
                              className="w-full text-left px-3 py-2.5 hover:bg-blue-50 text-sm border-b border-gray-50 last:border-0"
                            >
                              <div className="flex items-center gap-2">
                                <span className="font-mono text-blue-600 font-medium">#{a.numero}</span>
                                <span className="font-medium text-gray-900">{a.cliente}</span>
                                {a.asignadoA && <span className="text-blue-500 text-xs">({a.asignadoA.name})</span>}
                              </div>
                              <span className="text-gray-500 text-xs line-clamp-1">{a.descripcion}</span>
                            </button>
                          ))}
                        </div>
                      )}

                      {/* Initial avisos list for admin when no search is active */}
                      {!avisoSearch && (
                        <div className="pt-4">
                          {loadingAvisosIniciales ? (
                            <div className="flex items-center gap-2 text-sm text-gray-500 py-2">
                              <Loader2 className="w-4 h-4 animate-spin" /> Cargando avisos recientes...
                            </div>
                          ) : avisosIniciales.length === 0 ? (
                            <div className="text-sm text-gray-500 italic">No hay avisos pendientes recientes.</div>
                          ) : (
                            <div>
                              <p className="text-xs text-gray-600 mb-2 font-medium">Avisos pendientes y en curso ({avisosIniciales.length}):</p>
                              <div className="space-y-1 max-h-52 overflow-y-auto">
                                {avisosIniciales.map((a) => (
                                  <button
                                    key={a.id}
                                    type="button"
                                    onClick={() => handleSelectAviso(a)}
                                    className="w-full text-left px-3 py-2 rounded-lg hover:bg-blue-100 border border-gray-200 text-sm transition bg-white"
                                  >
                                    <div className="flex items-center gap-2">
                                      <span className="font-mono text-blue-600 font-medium">#{a.numero}</span>
                                      <span className="font-medium text-gray-900">{a.cliente}</span>
                                      {a.asignadoA && <span className="text-blue-500 text-xs">({a.asignadoA.name})</span>}
                                      <span className={`text-xs px-1.5 py-0.5 rounded ${a.estado === 'PENDIENTE' ? 'bg-yellow-100 text-yellow-800' :
                                        a.estado === 'ASIGNADO' ? 'bg-blue-100 text-blue-800' :
                                          'bg-purple-100 text-purple-800'
                                        }`}>{a.estado}</span>
                                    </div>
                                    <span className="text-gray-500 text-xs line-clamp-1">{a.descripcion}</span>
                                  </button>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  )}

                  {/* Modo CLIENTE: buscar cliente → mostrar sus avisos abiertos */}
                  {modoSeleccion === 'cliente' && (
                    <div className="space-y-3">
                      {!clienteSeleccionado ? (
                        <div className="relative">
                          <div className="relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                              type="text"
                              value={clienteSearch}
                              onChange={(e) => {
                                setClienteSearch(e.target.value);
                                searchClientes(e.target.value);
                                setShowClienteDropdown(true);
                              }}
                              onFocus={() => clienteResults.length > 0 && setShowClienteDropdown(true)}
                              onBlur={() => setTimeout(() => setShowClienteDropdown(false), 200)}
                              placeholder="Buscar cliente por nombre, CIF o teléfono..."
                              className="w-full pl-9 pr-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900 bg-white"
                            />
                            {searchingClientes && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-gray-400" />}
                          </div>
                          {showClienteDropdown && clienteResults.length > 0 && (
                            <div className="absolute z-20 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-48 overflow-y-auto">
                              {clienteResults.map((c) => (
                                <button
                                  key={c.id}
                                  type="button"
                                  onMouseDown={(e) => e.preventDefault()}
                                  onClick={() => handleSelectCliente(c)}
                                  className="w-full text-left px-3 py-2 hover:bg-blue-50 text-sm text-gray-900"
                                >
                                  <span className="font-medium">{c.nombre}</span>
                                  {c.cif && <span className="text-gray-500 ml-2">{c.cif}</span>}
                                </button>
                              ))}
                            </div>
                          )}
                        </div>
                      ) : (
                        <div>
                          <div className="flex items-center gap-2 px-3 py-2 bg-green-50 border border-green-200 rounded-lg mb-3">
                            <span className="text-sm text-green-800 font-medium flex-1">{clienteSeleccionado.nombre}</span>
                            <button onClick={clearCliente} className="text-green-600 hover:text-green-800">
                              <X className="w-4 h-4" />
                            </button>
                          </div>

                          {loadingAvisosCliente ? (
                            <div className="flex items-center gap-2 text-sm text-gray-500 py-2">
                              <Loader2 className="w-4 h-4 animate-spin" /> Cargando avisos...
                            </div>
                          ) : avisosDelCliente.length === 0 ? (
                            <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm text-amber-800">
                              <AlertTriangle className="w-4 h-4 inline mr-1" />
                              Este cliente no tiene avisos abiertos. Cree un aviso primero desde la sección de Avisos.
                            </div>
                          ) : (
                            <div>
                              <p className="text-xs text-gray-600 mb-2 font-medium">Avisos abiertos del cliente ({avisosDelCliente.length}):</p>
                              <div className="space-y-1 max-h-40 overflow-y-auto">
                                {avisosDelCliente.map((a) => (
                                  <button
                                    key={a.id}
                                    type="button"
                                    onClick={() => handleSelectAviso(a)}
                                    className="w-full text-left px-3 py-2 rounded-lg hover:bg-blue-50 border border-gray-200 text-sm transition"
                                  >
                                    <div className="flex items-center gap-2">
                                      <span className="font-mono text-blue-600 font-medium">#{a.numero}</span>
                                      <span className={`text-xs px-1.5 py-0.5 rounded ${a.estado === 'PENDIENTE' ? 'bg-yellow-100 text-yellow-800' :
                                        a.estado === 'ASIGNADO' ? 'bg-blue-100 text-blue-800' :
                                          'bg-purple-100 text-purple-800'
                                        }`}>{a.estado}</span>
                                      {a.asignadoA && <span className="text-gray-500 text-xs">({a.asignadoA.name})</span>}
                                    </div>
                                    <span className="text-gray-600 text-xs line-clamp-1">{a.descripcion}</span>
                                  </button>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  )}
                </>
              )}
            </div>
          ) : (
            /* ====== Aviso seleccionado: resumen ====== */
            <div className="bg-green-50 border border-green-200 rounded-xl p-4">
              <div className="flex items-start justify-between">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs text-green-600 font-medium">Aviso vinculado</span>
                    <span className="font-mono text-green-800 font-bold">#{avisoSeleccionado.numero}</span>
                    <span className={`text-xs px-1.5 py-0.5 rounded ${avisoSeleccionado.estado === 'PENDIENTE' ? 'bg-yellow-100 text-yellow-800' :
                      avisoSeleccionado.estado === 'ASIGNADO' ? 'bg-blue-100 text-blue-800' :
                        'bg-purple-100 text-purple-800'
                      }`}>{avisoSeleccionado.estado}</span>
                  </div>
                  <p className="text-sm font-medium text-green-900">{avisoSeleccionado.cliente}</p>
                  {avisoSeleccionado.descripcion && (
                    <p className="text-xs text-green-700 mt-0.5 line-clamp-2">{avisoSeleccionado.descripcion}</p>
                  )}
                </div>
                <button onClick={() => { clearAviso(); clearCliente(); }} className="text-green-600 hover:text-green-800">
                  <X className="w-4 h-4" />
                </button>
              </div>
            </div>
          )}

          {/* ====== PASO 2: Datos del parte (solo si hay aviso seleccionado) ====== */}
          {avisoSeleccionado && (
            <>
              {/* Tipo */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Tipo de parte *</label>
                <select
                  value={tipo}
                  onChange={(e) => setTipo(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white text-gray-900"
                >
                  {Object.entries(TIPO_PARTE_LABELS).map(([k, v]) => (
                    <option key={k} value={k}>{v}</option>
                  ))}
                </select>
              </div>

              {/* Descripción */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Descripción *</label>
                <textarea
                  value={descripcion}
                  onChange={(e) => setDescripcion(e.target.value)}
                  rows={3}
                  placeholder="Descripción del trabajo realizado..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm resize-none text-gray-900"
                />
              </div>

              {/* Técnicos */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-medium text-gray-700">Técnicos</label>
                  <button onClick={addTecnico} type="button" className="text-xs text-blue-600 hover:text-blue-800 flex items-center gap-1">
                    <Plus className="w-3 h-3" /> Añadir
                  </button>
                </div>
                {tecnicoIds.length === 0 && (
                  <p className="text-xs text-gray-400 py-1">Sin técnicos asignados</p>
                )}
                {tecnicoIds.map((t, idx) => (
                  <div key={idx} className="flex items-center gap-2 mb-2">
                    <select
                      value={t.tecnicoId}
                      onChange={(e) => updateTecnico(idx, 'tecnicoId', e.target.value)}
                      className="flex-1 px-3 py-1.5 border border-gray-300 rounded-lg text-sm bg-white text-gray-900"
                    >
                      <option value="">Seleccionar técnico...</option>
                      {tecnicosDisponibles.map(u => (
                        <option key={u.id} value={u.id}>{u.name || u.email}</option>
                      ))}
                    </select>
                    <select
                      value={t.rol}
                      onChange={(e) => updateTecnico(idx, 'rol', e.target.value)}
                      className="w-28 px-2 py-1.5 border border-gray-300 rounded-lg text-xs bg-white text-gray-700"
                    >
                      <option value="PRINCIPAL">Principal</option>
                      <option value="APOYO">Apoyo</option>
                    </select>
                    <button onClick={() => removeTecnico(idx)} className="text-red-400 hover:text-red-600">
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                ))}
              </div>

              {/* Fecha y horas */}
              <div className="grid grid-cols-3 gap-3">
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Fecha</label>
                  <input
                    type="date"
                    value={fechaInicio}
                    onChange={(e) => setFechaInicio(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Hora inicio</label>
                  <input
                    type="time"
                    value={horaInicio}
                    onChange={(e) => setHoraInicio(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Hora fin</label>
                  <input
                    type="time"
                    value={horaFin}
                    onChange={(e) => setHoraFin(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm text-gray-900"
                  />
                </div>
              </div>

              {horasCalculadasPreview && (
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800">
                  <Clock className="w-4 h-4 inline mr-1" /> {horasCalculadasPreview}
                </div>
              )}

              <label className="flex items-center gap-2 text-sm text-gray-700">
                <input
                  type="checkbox"
                  checked={descontarComida}
                  onChange={(e) => setDescontarComida(e.target.checked)}
                  className="rounded border-gray-300"
                />
                Descontar hora de comida (14:00-15:00)
              </label>

              {/* Facturación */}
              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2 text-sm text-gray-700">
                  <input
                    type="checkbox"
                    checked={facturable}
                    onChange={(e) => setFacturable(e.target.checked)}
                    className="rounded border-gray-300"
                  />
                  Facturable
                </label>
                {facturable && (
                  <div className="flex items-center gap-2">
                    <label className="text-xs text-gray-500">Importe est.</label>
                    <input
                      type="number"
                      step="0.01"
                      value={importeEstimado}
                      onChange={(e) => setImporteEstimado(e.target.value)}
                      placeholder="0.00"
                      className="w-28 px-3 py-1.5 border border-gray-300 rounded-lg text-sm text-gray-900"
                    />
                    <span className="text-xs text-gray-500">€</span>
                  </div>
                )}
              </div>

              {/* Presupuesto */}
              <div>
                <label className="flex items-center gap-2 text-sm text-gray-700 mb-2">
                  <input
                    type="checkbox"
                    checked={requierePresupuesto}
                    onChange={(e) => setRequierePresupuesto(e.target.checked)}
                    className="rounded border-gray-300"
                  />
                  Requiere presupuesto / Incidencia
                </label>
                {requierePresupuesto && (
                  <textarea
                    value={notasPresupuesto}
                    onChange={(e) => setNotasPresupuesto(e.target.value)}
                    rows={2}
                    placeholder="Notas para presupuesto: piezas necesarias, acciones, directrices..."
                    className="w-full px-3 py-2 border border-amber-300 bg-amber-50 rounded-lg text-sm resize-none text-gray-900"
                  />
                )}
              </div>

              {/* Materiales */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-medium text-gray-700">Materiales</label>
                  <button onClick={addMaterial} type="button" className="text-xs text-blue-600 hover:text-blue-800 flex items-center gap-1">
                    <Plus className="w-3 h-3" /> Añadir material
                  </button>
                </div>
                {materiales.map((m, idx) => (
                  <div key={idx} className="flex items-center gap-2 mb-2">
                    <input
                      type="text"
                      value={m.descripcion}
                      onChange={(e) => updateMaterial(idx, 'descripcion', e.target.value)}
                      placeholder="Material..."
                      className="flex-1 px-3 py-1.5 border border-gray-300 rounded-lg text-sm text-gray-900"
                    />
                    <input
                      type="number"
                      step="0.01"
                      value={m.cantidad}
                      onChange={(e) => updateMaterial(idx, 'cantidad', e.target.value)}
                      className="w-16 px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-gray-900 text-center"
                    />
                    <select
                      value={m.unidad}
                      onChange={(e) => updateMaterial(idx, 'unidad', e.target.value)}
                      className="w-20 px-2 py-1.5 border border-gray-300 rounded-lg text-xs bg-white text-gray-700"
                    >
                      {UNIDADES.map(u => <option key={u} value={u}>{u}</option>)}
                    </select>
                    <input
                      type="number"
                      step="0.01"
                      value={m.precioUnit}
                      onChange={(e) => updateMaterial(idx, 'precioUnit', e.target.value)}
                      placeholder="€/ud"
                      className="w-20 px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-gray-900"
                    />
                    <button onClick={() => removeMaterial(idx)} type="button" className="text-red-400 hover:text-red-600">
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                ))}
              </div>

              {/* Adjuntos (Documentos y fotos) */}
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <div>
                    <h4 className="text-sm font-medium text-gray-900 flex items-center gap-1">
                      <Paperclip className="w-4 h-4" /> Adjuntos para el parte
                    </h4>
                    <p className="text-xs text-gray-500 mt-0.5">Las imágenes o documentos seleccionados se subirán al guardar el parte.</p>
                  </div>
                  <div>
                    <input
                      ref={fileInputRef}
                      type="file"
                      multiple
                      accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
                      onChange={handleFileChange}
                      className="hidden"
                      id="nuevo-parte-file-upload"
                      disabled={saving}
                    />
                    <label
                      htmlFor="nuevo-parte-file-upload"
                      className={`text-xs px-3 py-1.5 rounded-lg font-medium border border-blue-300 text-blue-700 bg-white hover:bg-blue-50 cursor-pointer flex items-center gap-1 ${saving ? 'opacity-50 pointer-events-none' : ''}`}
                    >
                      <Plus className="w-3 h-3" /> Añadir archivo
                    </label>
                  </div>
                </div>

                {selectedFiles.length > 0 && (
                  <div className="space-y-2 mt-3">
                    {selectedFiles.map((f, idx) => (
                      <div key={idx} className="flex items-center gap-3 bg-white border border-gray-200 rounded-lg p-2.5 group">
                        <div className="flex-shrink-0">
                          {isImageFile(f.type) ? (
                            <ImageIcon className="w-5 h-5 text-green-600" />
                          ) : (
                            <FileText className="w-5 h-5 text-blue-600" />
                          )}
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm text-gray-900 font-medium truncate">{f.name}</p>
                          <p className="text-xs text-gray-400">{(f.size / 1024).toFixed(1)} KB</p>
                        </div>
                        <button
                          type="button"
                          onClick={() => removeFile(idx)}
                          disabled={saving}
                          className="text-red-400 hover:text-red-600 p-1 rounded-full hover:bg-red-50 disabled:opacity-50"
                          title="Eliminar de la selección"
                        >
                          <X className="w-4 h-4" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}
                {uploadProgress && (
                  <div className="mt-3 text-xs font-medium text-blue-600 flex items-center gap-2">
                    <Loader2 className="w-3 h-3 animate-spin" /> {uploadProgress}
                  </div>
                )}
              </div>

              {/* Observaciones */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Observaciones</label>
                <textarea
                  value={observaciones}
                  onChange={(e) => setObservaciones(e.target.value)}
                  rows={2}
                  placeholder="Notas adicionales..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm resize-none text-gray-900"
                />
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-white border-t px-6 py-4 flex justify-end gap-3">
          <button onClick={onClose} className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg">
            Cancelar
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving || !avisoSeleccionado}
            className="px-6 py-2 text-sm bg-[#1a365d] text-white rounded-lg hover:bg-[#2c5282] disabled:opacity-50 font-medium flex items-center gap-2"
          >
            {saving && <Loader2 className="w-4 h-4 animate-spin" />}
            Crear Parte
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}
