import { useState, useEffect, useCallback } from 'react';
import {
  DollarSign, FileText, Printer, TrendingUp,
  Download, PieChart as PieIcon,
  Clock, RefreshCw, UserCheck, ListChecks, ChevronRight, Users, ArrowLeft,
  History, CheckCircle, XCircle
} from 'lucide-react';
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer,
} from 'recharts';
import { dashboardService, type DashboardData } from '../services/dashboardService';
import { translateStatus } from '../utils/translations';
import { useAuthStore } from '../store/authStore';
import api from '../services/api';
import { reportService } from '../services/reportService';
import type {
  CashierStat,
  RecentTransaction,
  AuditLogItem
} from '../types/Dashboard';

const getLocalDateString = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

export default function Dashboard() {
  const { role } = useAuthStore();
  const [data, setData] = useState<DashboardData | null>(null);
  const [cashiers, setCashiers] = useState<CashierStat[]>([]);
  const [recentTransactions, setRecentTransactions] = useState<RecentTransaction[]>([]);
  const [loading, setLoading] = useState(true);

  // --- NUEVOS ESTADOS PARA MONITOR INTEGRADO ---
  const [selectedCashier, setSelectedCashier] = useState<{ id: number, name: string } | null>(null);
  const [selectedCashierLogs, setSelectedCashierLogs] = useState<AuditLogItem[]>([]);
  const [loadingLogs, setLoadingLogs] = useState(false);

  const todayStr = getLocalDateString(new Date());
  const [dates, setDates] = useState({ from: todayStr, to: todayStr });

  const loadCashierLogs = useCallback(async (userId: number) => {
    setLoadingLogs(true);
    try {
      const res = await api.get(`/reports/audit/user/${userId}`);
      setSelectedCashierLogs(res.data);
    } catch {
      console.error("Error cargando logs");
    } finally {
      setLoadingLogs(false);
    }
  }, []);

  const loadDashboardData = useCallback(async () => {
    if (new Date(dates.from) > new Date(dates.to)) return;

    try {
      setLoading(true);

      if (role === 'Admin') {
        if (selectedCashier) {
          const res = await api.get(`/reports/cashier-detail/${selectedCashier.id}`, {
            params: { from: dates.from, to: dates.to }
          });
          setData(res.data);
          // Cargar logs del cajero seleccionado
          loadCashierLogs(selectedCashier.id);
        } else {
          const stats = await dashboardService.getStats(dates.from, dates.to);
          setData(stats);
          const usersRes = await api.get('/users');
          setCashiers(usersRes.data.filter((u: CashierStat) => u.role === 'Cajero'));
        }
      } else {
        const res = await api.get('/reports/cashier', {
          params: { from: dates.from, to: dates.to }
        });
        setData(res.data);
      }

      const params: Record<string, unknown> = {};
      if (selectedCashier) params.userId = selectedCashier.id;
      const recentRes = await api.get('/listings', { params });
      setRecentTransactions(recentRes.data.slice(0, 5));

    } catch (error) {
      console.error("Error cargando dashboard:", error);
    } finally {
      setLoading(false);
    }
  }, [dates, role, selectedCashier, loadCashierLogs]);

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

  const setQuickRange = (days: number) => {
    const now = new Date();
    const start = new Date();
    start.setDate(now.getDate() - days);
    setDates({ from: getLocalDateString(start), to: getLocalDateString(now) });
  };

  const handleExport = async () => {
    try {
      await reportService.exportCierre(dates.from, dates.to, selectedCashier?.id);
    } catch {
      alert("Error al generar el reporte");
    }
  };

  const getAuditIcon = (action: string) => {
    if (action === 'Aprobar') return <CheckCircle className="text-green-500" size={14} />;
    if (action === 'Rechazar') return <XCircle className="text-red-500" size={14} />;
    return <Clock className="text-blue-500" size={14} />;
  };

  if (loading && !data) {
    return (
      <div className="flex flex-col items-center justify-center h-64 text-gray-500">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
        <p className="font-medium">Sincronizando información...</p>
      </div>
    );
  }

  if (!data) return null;

  const isInvalidRange = new Date(dates.from) > new Date(dates.to);

  return (
    <div className="space-y-6">
      {/* HEADER UNIFICADO */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white p-4 rounded-xl border border-gray-200 shadow-sm transition-all">
        <div className="flex items-center gap-4">
          {selectedCashier && (
            <button
              onClick={() => setSelectedCashier(null)}
              className="p-2 hover:bg-gray-100 rounded-full text-gray-500 transition-colors"
              title="Volver a Vista Global"
            >
              <ArrowLeft size={20} />
            </button>
          )}
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-xl font-bold text-gray-800">
                {role === 'Admin'
                  ? (selectedCashier ? `Auditoría: ${selectedCashier.name}` : 'Resumen Gerencial')
                  : 'Mi Rendimiento'}
              </h1>
              {loading && <RefreshCw size={14} className="animate-spin text-blue-500" />}
            </div>
            <div className="flex items-center gap-2 text-sm text-gray-500">
              <Clock size={14} />
              <span>{new Date(dates.from).toLocaleDateString()} - {new Date(dates.to).toLocaleDateString()}</span>
            </div>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <div className="flex bg-gray-100 p-1 rounded-lg">
            <button onClick={() => setQuickRange(0)} className={`px-3 py-1 text-xs font-bold rounded transition-all ${dates.from === todayStr ? 'bg-white shadow text-blue-600' : 'text-gray-500'}`}>HOY</button>
            <button onClick={() => setQuickRange(7)} className={`px-3 py-1 text-xs font-bold rounded transition-all ${dates.from !== todayStr ? 'bg-white shadow text-blue-600' : 'text-gray-500'}`}>7D</button>
          </div>

          <div className="flex items-center gap-2 border-l pl-3 border-gray-200">
            <input type="date" value={dates.from} onChange={(e) => setDates({ ...dates, from: e.target.value })} className={`text-xs border ${isInvalidRange ? 'border-red-500 bg-red-50' : 'border-gray-300 bg-gray-50'} rounded p-1.5 outline-none focus:ring-2 focus:ring-blue-500/20`} />
            <span className="text-gray-400 text-xs">-</span>
            <input type="date" value={dates.to} onChange={(e) => setDates({ ...dates, to: e.target.value })} className={`text-xs border ${isInvalidRange ? 'border-red-500 bg-red-50' : 'border-gray-300 bg-gray-50'} rounded p-1.5 outline-none focus:ring-2 focus:ring-blue-500/20`} />
          </div>

          <button
            onClick={handleExport}
            className="flex items-center gap-2 bg-gray-900 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-gray-700 transition shadow-md"
          >
            <Download size={16} />
            {role === 'Admin' ? (selectedCashier ? 'DESCARGAR CAJA' : 'DESCARGAR CIERRE GLOBAL') : 'MI ACTIVIDAD'}
          </button>
        </div>
      </div>

      {/* KPIs */}
      {(role === 'Cajero' || selectedCashier) ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <KpiCard title="Recaudación Caja" value={`$${(data.myRevenue ?? 0).toLocaleString()}`} trend="Ingresos" icon={<DollarSign />} color="bg-green-50 text-green-600" />
          <KpiCard title="Avisos Procesados" value={(data.myAdsCount ?? 0).toString()} trend="Cargas" icon={<UserCheck />} color="bg-blue-50 text-blue-700" />
          <KpiCard title="En Revisión" value={(data.myPendingAds ?? 0).toString()} trend="Pendientes" icon={<ListChecks />} color="bg-orange-50 text-orange-700" />
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <KpiCard title="Recaudación" value={`$${data.revenueToday.toLocaleString()}`} trend="Total" icon={<DollarSign />} color="bg-green-50 text-green-600" />
          <KpiCard title="Avisos Vendidos" value={data.adsToday.toString()} trend="Aprobados" icon={<FileText />} color="bg-blue-50 text-blue-600" />
          <KpiCard title="Ocupación Papel" value={`${Math.round(data.paperOccupation)}%`} trend="Mañana" progress={data.paperOccupation} icon={<Printer />} color="bg-orange-50 text-orange-600" />
          <KpiCard title="Ticket Promedio" value={`$${Math.round(data.ticketAverage).toLocaleString()}`} trend="Promedio" icon={<TrendingUp />} color="bg-purple-50 text-purple-600" />
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 bg-white p-6 rounded-xl border border-gray-200 shadow-sm">
          <h3 className="font-bold text-gray-700 mb-6 flex items-center gap-2"><TrendingUp size={18} className="text-blue-500" /> Evolución de Ingresos</h3>
          <div className="h-72 relative">
            {role === 'Admin' && !selectedCashier ? (
              <ResponsiveContainer width="100%" height="100%" minWidth={0} debounce={50}>
                <LineChart data={data.weeklyTrend}>
                  <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#F3F4F6" />
                  <XAxis dataKey="day" axisLine={false} tickLine={false} tick={{ fill: '#9CA3AF', fontSize: 11 }} dy={10} />
                  <YAxis axisLine={false} tickLine={false} tick={{ fill: '#9CA3AF', fontSize: 11 }} />
                  <Tooltip formatter={(val: number | undefined) => [`$${Number(val ?? 0).toLocaleString()}`, "Ventas"]} contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgba(0,0,0,0.1)' }} />
                  <Line type="monotone" dataKey="amount" stroke="#3B82F6" strokeWidth={4} dot={{ r: 4, fill: '#3B82F6', strokeWidth: 2, stroke: '#fff' }} activeDot={{ r: 6, strokeWidth: 0 }} />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="absolute inset-0 flex items-center justify-center bg-gray-50/50 rounded-xl text-gray-400 italic text-sm">
                Gráfico de tendencia disponible en vista gerencial global
              </div>
            )}
          </div>
        </div>

        {/* MONITOR INTEGRADO (LISTA O AUDITORÍA) */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm flex flex-col overflow-hidden">
          {role === 'Admin' && !selectedCashier ? (
            <>
              <div className="p-4 border-b bg-gray-50/50 flex justify-between items-center">
                <h3 className="font-bold text-gray-700 flex items-center gap-2">
                  <Users size={18} className="text-blue-500" /> Monitor de Cajeros
                </h3>
              </div>
              <div className="p-4 space-y-3 overflow-y-auto flex-1">
                {cashiers.map(c => (
                  <div
                    key={c.id}
                    onClick={() => setSelectedCashier({ id: c.id, name: c.username })}
                    className="flex items-center justify-between p-3 rounded-xl border border-gray-100 bg-white hover:bg-blue-50 hover:border-blue-200 transition-all cursor-pointer group"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center text-xs font-bold text-gray-500 group-hover:text-blue-600 transition-colors">
                        {c.username.charAt(0).toUpperCase()}
                      </div>
                      <span className="text-sm font-bold text-gray-700">{c.username}</span>
                    </div>
                    <ChevronRight size={16} className="text-gray-300 group-hover:text-blue-500" />
                  </div>
                ))}
              </div>
            </>
          ) : role === 'Admin' && selectedCashier ? (
            <>
              <div className="p-4 border-b bg-blue-600 text-white flex justify-between items-center">
                <div className="flex items-center gap-2">
                  <History size={18} />
                  <h3 className="font-bold text-sm truncate">Logs: {selectedCashier.name}</h3>
                </div>
                <button
                  onClick={() => setSelectedCashier(null)}
                  className="text-[10px] bg-white/20 hover:bg-white/30 px-2 py-1 rounded font-bold transition-colors"
                >
                  CERRAR
                </button>
              </div>

              <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-white">
                {loadingLogs ? (
                  <div className="h-full flex items-center justify-center text-gray-400 animate-pulse text-xs italic">Consultando actividad...</div>
                ) : selectedCashierLogs.length === 0 ? (
                  <div className="h-full flex items-center justify-center text-gray-400 text-xs italic">Sin actividad registrada</div>
                ) : (
                  selectedCashierLogs.map(log => (
                    <div key={log.id} className="relative pl-6 pb-4 border-l border-gray-100 last:pb-0">
                      <div className="absolute left-[-7px] top-1 bg-white p-0.5">
                        {getAuditIcon(log.action)}
                      </div>
                      <div className="text-[11px] font-bold text-gray-700 flex justify-between">
                        <span>{log.action}</span>
                        <span className="font-normal text-gray-400 font-mono">
                          {new Date(log.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                      <p className="text-[10px] text-gray-500 mt-0.5 line-clamp-2 leading-relaxed">{log.details}</p>
                    </div>
                  ))
                )}
              </div>
            </>
          ) : (
            <div className="flex flex-col items-center justify-center h-full text-center space-y-4 p-6">
              <div className="p-4 bg-blue-50 rounded-full text-blue-600"><PieIcon size={32} /></div>
              <div>
                <h4 className="font-bold text-gray-700">Mi Puesto</h4>
                <p className="text-xs text-gray-400">Visualizando tus métricas de hoy.</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* TABLA DE ÚLTIMOS MOVIMIENTOS */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
        <div className="p-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
          <h3 className="font-bold text-gray-700">
            {role === 'Admin' ? (selectedCashier ? `Cargas de ${selectedCashier.name}` : 'Últimos Avisos Procesados') : 'Mis Últimas Cargas'}
          </h3>
          <a href="/listings" className="text-sm text-blue-600 font-semibold hover:underline">Ver todo</a>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse text-sm">
            <thead className="text-xs font-bold text-gray-400 uppercase tracking-wider bg-gray-50/50">
              <tr>
                <th className="p-4 border-b border-gray-100">Fecha / Hora</th>
                <th className="p-4 border-b border-gray-100">Rubro / Título</th>
                <th className="p-4 border-b border-gray-100">Monto (Fee)</th>
                <th className="p-4 border-b border-gray-100">Estado</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {recentTransactions.map(t => (
                <tr key={t.id} className="hover:bg-gray-50/80 transition-colors">
                  <td className="p-4 text-gray-500 font-medium">
                    <div>{new Date(t.createdAt).toLocaleDateString()}</div>
                    <div className="text-[10px] opacity-60 font-mono">{new Date(t.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</div>
                  </td>
                  <td className="p-4">
                    <div className="font-bold text-gray-700">{t.title}</div>
                    <div className="text-[11px] text-gray-400 uppercase tracking-tighter">{t.categoryName || 'General'}</div>
                  </td>
                  <td className="p-4 font-black text-blue-600">${t.adFee?.toLocaleString() || "0"}</td>
                  <td className="p-4">
                    <span className={`flex items-center gap-1.5 font-bold ${t.status === 'Published' ? 'text-green-600' : 'text-orange-500'}`}>
                      <div className={`w-1.5 h-1.5 rounded-full ${t.status === 'Published' ? 'bg-green-600' : 'bg-orange-500'}`}></div>
                      {translateStatus(t.status)}
                    </span>
                  </td>
                </tr>
              ))}
              {recentTransactions.length === 0 && (
                <tr><td colSpan={4} className="p-8 text-center text-gray-400 italic">No hay transacciones para mostrar.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

interface KpiCardProps {
  title: string;
  value: string | number;
  trend: string;
  icon: React.ReactNode;
  color: string;
  progress?: number;
}

function KpiCard({ title, value, trend, icon, color, progress }: KpiCardProps) {
  return (
    <div className="bg-white p-5 rounded-xl border border-gray-200 shadow-sm hover:shadow-md transition-all group">
      <div className="flex justify-between items-center mb-4">
        <div className={`p-2.5 rounded-lg transition-colors ${color}`}>{icon}</div>
        <div className="text-[10px] font-black px-2 py-1 rounded-full uppercase bg-gray-100 text-gray-500 group-hover:bg-gray-200 transition-colors">
          {trend}
        </div>
      </div>
      <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">{title}</p>
      <h4 className="text-2xl font-black text-gray-800 mt-1">{value}</h4>
      {progress !== undefined && (
        <div className="mt-4 w-full bg-gray-100 rounded-full h-2">
          <div className={`h-2 rounded-full transition-all duration-700 ${progress > 90 ? 'bg-red-500' : 'bg-orange-500'}`} style={{ width: `${progress}%` }}></div>
        </div>
      )}
    </div>
  );
}