'use client';

import { useState, useEffect, useCallback } from 'react';
import { AnimatePresence } from 'framer-motion';
import {
  Plus, Search, Filter, RefreshCw, Download, FileText,
  ChevronRight, Clock, User, Wrench, CheckCircle, Flag,
  X, DollarSign
} from 'lucide-react';
import {
  TIPO_PARTE_LABELS, TIPO_PARTE_COLORS,
  ESTADO_PARTE_LABELS, ESTADO_PARTE_COLORS,
  TIPOS_PARTE, ESTADOS_PARTE,
} from '@/lib/partes/constants';
import NuevoParteModal from './nuevo-parte-modal';
import ParteDetailModal from './parte-detail-modal';

interface ParteListItem {
  id: string;
  numero: number;
  tipo: string;
  estado: string;
  descripcion: string;
  clienteNombre: string | null;
  clienteRef: { id: string; nombre: string } | null;
  aviso: { id: string; numero: number; cliente: string; estado: string } | null;
  tecnico: { id: string; name: string } | null;
  tecnicos: { tecnico: { id: string; name: string }; rol: string }[];
  horaInicio: string | null;
  horaFin: string | null;
  horasCalculadas: number | null;
  fechaInicio: string | null;
  facturable: boolean;
  facturado: boolean;
  numFactura: string | null;
  importeEstimado: number | null;
  firmado: boolean;
  requierePresupuesto: boolean;
  _count: { materiales: number };
  createdAt: string;
}

export default function PartesContent({ userRole, userId }: { userRole: string; userId: string }) {
  const [partes, setPartes] = useState<ParteListItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [busqueda, setBusqueda] = useState('');
  const [filtroTipo, setFiltroTipo] = useState('');
  const [filtroEstado, setFiltroEstado] = useState('');
  const [filtroPendienteFacturar, setFiltroPendienteFacturar] = useState(false);
  const [filtroRequierePresupuesto, setFiltroRequierePresupuesto] = useState(false);
  const [filtroDesde, setFiltroDesde] = useState('');
  const [filtroHasta, setFiltroHasta] = useState('');
  const [showNuevoModal, setShowNuevoModal] = useState(false);
  const [selectedParteId, setSelectedParteId] = useState<string | null>(null);
  const [showFilters, setShowFilters] = useState(false);

  const canCreate = true; // todos los usuarios pueden crear partes

  const fetchPartes = useCallback(async () => {
    try {
      const params = new URLSearchParams();
      if (busqueda) params.set('q', busqueda);
      if (filtroTipo) params.set('tipo', filtroTipo);
      if (filtroEstado) params.set('estado', filtroEstado);
      if (filtroPendienteFacturar) params.set('pendienteFacturar', 'true');
      if (filtroRequierePresupuesto) params.set('requierePresupuesto', 'true');
      if (filtroDesde) params.set('desde', filtroDesde);
      if (filtroHasta) params.set('hasta', filtroHasta);
      params.set('limit', '200');

      const res = await fetch(`/api/partes?${params}`);
      const data = await res.json();
      if (data.partes) {
        setPartes(data.partes);
        setTotal(data.total);
      }
    } catch (err) {
      console.error('Error fetching partes:', err);
    } finally {
      setLoading(false);
    }
  }, [busqueda, filtroTipo, filtroEstado, filtroPendienteFacturar, filtroRequierePresupuesto, filtroDesde, filtroHasta]);

  useEffect(() => {
    fetchPartes();
  }, [fetchPartes]);

  const handleExportCSV = async () => {
    const params = new URLSearchParams();
    if (filtroTipo) params.set('tipo', filtroTipo);
    if (filtroEstado) params.set('estado', filtroEstado);
    if (filtroPendienteFacturar) params.set('pendienteFacturar', 'true');
    if (filtroDesde) params.set('desde', filtroDesde);
    if (filtroHasta) params.set('hasta', filtroHasta);

    const a = document.createElement('a');
    a.href = `/api/partes/exportar?${params}`;
    a.download = `partes_${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
  };

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

  const getTecnicosStr = (parte: ParteListItem) => {
    if (parte.tecnicos.length > 0) {
      return parte.tecnicos.map(t => t.tecnico.name).join(', ');
    }
    return parte.tecnico?.name || '-';
  };

  const clearFilters = () => {
    setFiltroTipo('');
    setFiltroEstado('');
    setFiltroPendienteFacturar(false);
    setFiltroRequierePresupuesto(false);
    setFiltroDesde('');
    setFiltroHasta('');
  };

  const hasActiveFilters = filtroTipo || filtroEstado || filtroPendienteFacturar || filtroRequierePresupuesto || filtroDesde || filtroHasta;

  return (
    <div className="p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Partes de Trabajo</h1>
          <p className="text-sm text-gray-500 mt-1">{total} partes en total</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={handleExportCSV}
            className="flex items-center gap-2 border border-gray-300 text-gray-700 px-3 py-2 rounded-lg text-sm hover:bg-gray-50 transition-colors"
          >
            <Download className="w-4 h-4" />
            Exportar CSV
          </button>
          {canCreate && (
            <button
              onClick={() => setShowNuevoModal(true)}
              className="flex items-center gap-2 bg-[#1a365d] hover:bg-[#2c5282] text-white px-4 py-2 rounded-lg font-medium transition-colors text-sm"
            >
              <Plus className="w-4 h-4" />
              Nuevo Parte
            </button>
          )}
        </div>
      </div>

      {/* Toolbar */}
      <div className="flex flex-col gap-3 mb-6">
        <div className="flex flex-col md:flex-row gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Buscar por cliente, descripción, factura..."
              value={busqueda}
              onChange={(e) => setBusqueda(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#3182ce] focus:border-transparent outline-none text-gray-900"
            />
          </div>
          <div className="flex items-center gap-2">
            <select
              value={filtroTipo}
              onChange={(e) => setFiltroTipo(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white text-gray-700"
            >
              <option value="">Todos los tipos</option>
              {Object.entries(TIPO_PARTE_LABELS).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
            <select
              value={filtroEstado}
              onChange={(e) => setFiltroEstado(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white text-gray-700"
            >
              <option value="">Todos los estados</option>
              {Object.entries(ESTADO_PARTE_LABELS).map(([k, v]) => (
                <option key={k} value={k}>{v}</option>
              ))}
            </select>
            <button
              onClick={() => setShowFilters(!showFilters)}
              className={`p-2 rounded-lg border transition-colors ${showFilters || hasActiveFilters ? 'border-blue-300 bg-blue-50 text-blue-700' : 'border-gray-300 text-gray-500 hover:bg-gray-50'}`}
              title="Más filtros"
            >
              <Filter className="w-4 h-4" />
            </button>
            <button
              onClick={() => { setLoading(true); fetchPartes(); }}
              className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg"
              title="Refrescar"
            >
              <RefreshCw className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* Advanced filters */}
        {showFilters && (
          <div className="bg-gray-50 rounded-lg p-4 flex flex-wrap gap-3 items-end">
            <div>
              <label className="block text-xs text-gray-500 mb-1">Desde</label>
              <input
                type="date"
                value={filtroDesde}
                onChange={(e) => setFiltroDesde(e.target.value)}
                className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm text-gray-700"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1">Hasta</label>
              <input
                type="date"
                value={filtroHasta}
                onChange={(e) => setFiltroHasta(e.target.value)}
                className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm text-gray-700"
              />
            </div>
            <label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
              <input
                type="checkbox"
                checked={filtroPendienteFacturar}
                onChange={(e) => setFiltroPendienteFacturar(e.target.checked)}
                className="rounded border-gray-300"
              />
              Pendiente de facturar
            </label>
            <label className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
              <input
                type="checkbox"
                checked={filtroRequierePresupuesto}
                onChange={(e) => setFiltroRequierePresupuesto(e.target.checked)}
                className="rounded border-gray-300"
              />
              Requiere presupuesto
            </label>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="text-xs text-red-600 hover:text-red-800 flex items-center gap-1"
              >
                <X className="w-3 h-3" /> Limpiar filtros
              </button>
            )}
          </div>
        )}
      </div>

      {/* Table */}
      {loading ? (
        <div className="flex items-center justify-center py-20">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#1a365d]"></div>
        </div>
      ) : (
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  <th className="px-4 py-3">#</th>
                  <th className="px-4 py-3">Tipo</th>
                  <th className="px-4 py-3">Estado</th>
                  <th className="px-4 py-3">Cliente</th>
                  <th className="px-4 py-3">Descripción</th>
                  <th className="px-4 py-3">Técnicos</th>
                  <th className="px-4 py-3">Fecha</th>
                  <th className="px-4 py-3">Horas</th>
                  <th className="px-4 py-3">Facturación</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {partes.length === 0 ? (
                  <tr>
                    <td colSpan={10} className="px-4 py-12 text-center text-gray-400">
                      <FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
                      No se encontraron partes de trabajo
                    </td>
                  </tr>
                ) : (
                  partes.map((parte) => (
                    <tr
                      key={parte.id}
                      className="hover:bg-gray-50 cursor-pointer transition-colors"
                      onClick={() => setSelectedParteId(parte.id)}
                    >
                      <td className="px-4 py-3 text-sm font-mono text-gray-500">
                        <div className="flex items-center gap-1">
                          {parte.numero}
                          {parte.requierePresupuesto && <Flag className="w-3 h-3 text-amber-500" />}
                          {parte.firmado && <CheckCircle className="w-3 h-3 text-green-500" />}
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-1 rounded font-medium ${TIPO_PARTE_COLORS[parte.tipo]}`}>
                          {TIPO_PARTE_LABELS[parte.tipo]}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-1 rounded-full font-medium ${ESTADO_PARTE_COLORS[parte.estado]}`}>
                          {ESTADO_PARTE_LABELS[parte.estado]}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm font-medium text-gray-900 max-w-[150px] truncate">
                        {parte.clienteNombre || parte.clienteRef?.nombre || parte.aviso?.cliente || '-'}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600 max-w-[200px] truncate">
                        {parte.descripcion}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600 max-w-[120px] truncate">
                        {getTecnicosStr(parte)}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-500">
                        {parte.fechaInicio ? formatDate(parte.fechaInicio) : '-'}
                        {parte.horaInicio && (
                          <span className="block text-gray-400">{parte.horaInicio}{parte.horaFin ? ` - ${parte.horaFin}` : ''}</span>
                        )}
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-600">
                        {parte.horasCalculadas != null ? `${parte.horasCalculadas}h` : '-'}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-1">
                          {parte.facturable ? (
                            parte.facturado ? (
                              <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded-full flex items-center gap-1">
                                <DollarSign className="w-3 h-3" /> {parte.numFactura || 'Facturado'}
                              </span>
                            ) : (
                              <span className="text-xs bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full">Pdte. facturar</span>
                            )
                          ) : (
                            <span className="text-xs text-gray-400">No facturable</span>
                          )}
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <ChevronRight className="w-4 h-4 text-gray-400" />
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Modals */}
      <AnimatePresence>
        {showNuevoModal && (
          <NuevoParteModal
            onClose={() => setShowNuevoModal(false)}
            onCreated={() => { setShowNuevoModal(false); fetchPartes(); }}
            userRole={userRole}
            userId={userId}
          />
        )}
        {selectedParteId && (
          <ParteDetailModal
            parteId={selectedParteId}
            userRole={userRole}
            onClose={() => { setSelectedParteId(null); fetchPartes(); }}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
