import { useState, useEffect, useCallback } from 'react';
import { cashRegisterService } from '../services/cashRegisterService';
import type { GlobalReport, ReportItem } from '../types/Report';
import {
  Printer,
  Clock,
  CheckCircle,
  RefreshCw,
  Wallet,
  CreditCard,
  Banknote,
  Search,
  Filter,
  ArrowRightLeft
} from 'lucide-react';
import CashClosingModal from '../components/CashClosingModal';
import { motion, AnimatePresence } from 'framer-motion';
import { useToast } from '../context/use-toast';

export default function CashRegisterPage() {
  const { showToast } = useToast();
  const [data, setData] = useState<GlobalReport | null>(null);
  const [loading, setLoading] = useState(true);
  const [showClosingModal, setShowClosingModal] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");

  const loadData = useCallback(async (isManual = false) => {
    setLoading(true);
    try {
      const result = await cashRegisterService.getDailyStatus();
      setData(result);
      if (isManual) showToast('Datos de caja sincronizados correctamente.', 'success');
    } catch {
      showToast('Error al conectar con el servidor de tesorería.', 'error');
    } finally {
      setLoading(false);
    }
  }, [showToast]);

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

  const handleCerrarCaja = () => {
    setShowClosingModal(true);
  };

  const handleClosingComplete = () => {
    loadData();
  };

  const formatCurrency = (val: number) =>
    val.toLocaleString('es-AR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  // SOLUCIÓN AL HORARIO: Forzar interpretación UTC
  const formatLocalTime = (dateString: string) => {
    if (!dateString) return "--:--";

    // 1. Convertimos el formato de SQL (espacio) a ISO (T)
    let isoStr = dateString.replace(" ", "T");

    // 2. Si no tiene la 'Z' al final, se la agregamos para decirle al navegador: "Esto es UTC"
    if (!isoStr.endsWith("Z")) {
      isoStr += "Z";
    }

    const date = new Date(isoStr);

    return date.toLocaleTimeString('es-AR', {
      hour: '2-digit',
      minute: '2-digit',
      hour12: true,
      timeZone: 'America/Argentina/Buenos_Aires' // Forzamos la zona de Argentina
    });
  };

  const filteredItems = data?.items.filter((item: ReportItem) =>
    item.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    item.category?.toLowerCase().includes(searchTerm.toLowerCase())
  ) || [];

  if (loading && !data) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-4 text-slate-500">
        <RefreshCw size={32} className="animate-spin text-blue-600" />
        <span className="font-black tracking-[0.2em] text-[10px] uppercase">Sincronizando flujos...</span>
      </div>
    );
  }

  return (
    <div className="p-5 w-full flex flex-col gap-5 bg-slate-50/50 h-full overflow-hidden">

      {/* Header Section Refinado */}
      <div className="flex justify-between items-start">
        <motion.div initial={{ opacity: 0, x: -15 }} animate={{ opacity: 1, x: 0 }}>
          <span className="text-[9px] font-black text-blue-600 uppercase tracking-[0.3em] mb-0.5 block">Control de Tesorería</span>
          <h2 className="text-xl font-black text-slate-900 tracking-tight uppercase flex items-center gap-2">
            <span className="bg-blue-600 w-1.5 h-5 rounded-full"></span>
            Caja Diaria
          </h2>
          <div className="flex items-center gap-2 mt-1.5">
            <div className="flex items-center gap-1.5 px-2 py-0.5 bg-white border border-slate-200 rounded-lg text-[9px] font-black text-slate-500 shadow-sm uppercase">
              <Clock size={10} className="text-blue-500" />
              TURNO: {new Date().toLocaleDateString('es-AR', { weekday: 'short', day: 'numeric', month: 'short' })}
            </div>
          </div>
        </motion.div>

        <motion.div initial={{ opacity: 0, x: 15 }} animate={{ opacity: 1, x: 0 }} className="flex gap-3">
          <button
            onClick={() => loadData(true)}
            className="p-2 bg-white border border-slate-200 text-slate-500 hover:text-blue-600 hover:border-blue-200 rounded-xl transition-all shadow-sm active:scale-95"
          >
            <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
          </button>
          <button
            onClick={handleCerrarCaja}
            className="bg-slate-900 text-white px-5 py-2 rounded-xl font-black text-[10px] flex items-center gap-2 hover:bg-black transition-all shadow-lg shadow-slate-200 active:scale-95 group tracking-widest"
          >
            <Printer size={14} className="text-blue-400" />
            CERRAR CAJA (F4)
          </button>
        </motion.div>
      </div>

      {/* KPI Section Refinado (Más compacto) */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
        <KPICard
          icon={<Banknote size={18} />}
          label="Recaudación Turno"
          value={`$ ${formatCurrency(data?.totalRevenue || 0)}`}
          badge="EN EFECTIVO"
          color="emerald"
        />
        <KPICard
          icon={<CheckCircle size={18} />}
          label="Avisos Procesados"
          value={data?.totalAds || 0}
          badge="OPERACIONES"
          color="blue"
        />
        <motion.div
          whileHover={{ y: -3 }}
          className="bg-slate-900 p-4 rounded-[1.5rem] shadow-xl flex flex-col justify-between text-white overflow-hidden relative border-b-4 border-blue-600"
        >
          <div className="absolute top-0 right-0 w-20 h-20 bg-blue-600/10 rounded-full -mr-8 -mt-8 blur-2xl"></div>
          <div className="flex justify-between items-start mb-2 relative z-10">
            <div className="p-2 bg-white/5 rounded-xl text-blue-400"><Wallet size={16} /></div>
            <span className="text-[8px] font-black text-blue-400 bg-blue-500/10 border border-blue-500/20 px-2 py-0.5 rounded-md uppercase tracking-widest">PRÓXIMO CIERRE</span>
          </div>
          <div className="relative z-10">
            <div className="text-slate-500 text-[8px] font-black uppercase tracking-widest mb-0.5">Arqueo Estimado</div>
            <div className="text-2xl font-mono font-black text-white leading-none">
              $ {formatCurrency(data?.totalRevenue || 0)}
            </div>
            <div className="mt-2 flex gap-1 opacity-20">
              {[1, 2, 3, 4, 5, 6].map(i => <div key={i} className="h-0.5 flex-1 bg-white rounded-full"></div>)}
            </div>
          </div>
        </motion.div>
      </div>

      {/* Table Section (Contraste aumentado) */}
      <div className="flex-1 bg-white rounded-[1.8rem] shadow-xl shadow-slate-200/50 border border-slate-200 overflow-hidden flex flex-col min-h-0">
        <div className="px-5 py-3 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
          <div className="flex items-center gap-3 flex-1">
            <div className="relative max-w-xs w-full">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" size={14} />
              <input
                type="text"
                placeholder="Buscar movimiento..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-xl text-xs font-bold focus:ring-4 focus:ring-blue-500/5 outline-none transition-all placeholder:text-slate-500"
              />
            </div>
            <button className="flex items-center gap-2 px-3 py-2 bg-white border border-slate-200 rounded-xl text-[9px] font-black text-slate-600 hover:border-slate-400 transition-all shadow-sm uppercase tracking-tighter">
              <Filter size={12} /> Filtrar Pagos
            </button>
          </div>
          <div className="flex items-center gap-2 text-[9px] font-black uppercase tracking-widest text-emerald-600 bg-emerald-50 px-3 py-1 rounded-full border border-emerald-100">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
            Turno Activo
          </div>
        </div>

        <div className="overflow-y-auto flex-1 custom-scrollbar">
          <table className="w-full text-left border-collapse">
            <thead className="bg-slate-50 text-slate-600 text-[9px] uppercase font-black tracking-[0.15em] sticky top-0 z-10 backdrop-blur-md border-b border-slate-100">
              <tr>
                <th className="px-6 py-4">ID Operación</th>
                <th className="px-6 py-4 text-center">Horario (GMT-3)</th>
                <th className="px-6 py-4">Detalle del Aviso</th>
                <th className="px-6 py-4">Rubro</th>
                <th className="px-6 py-4 text-right">Importe</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50 text-xs">
              <AnimatePresence mode="popLayout">
                {filteredItems.map((item: ReportItem, idx: number) => (
                  <motion.tr
                    key={item.id}
                    initial={{ opacity: 0, y: 5 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: idx * 0.02 }}
                    className="hover:bg-blue-50/40 transition-all group"
                  >
                    <td className="px-6 py-4 font-mono text-slate-500 font-bold">#{item.id.toString().padStart(6, '0')}</td>
                    <td className="px-6 py-4 text-center">
                      <div className="inline-flex items-center gap-1.5 text-slate-800 font-black bg-slate-100 px-2.5 py-1 rounded-lg">
                        <Clock size={12} className="text-blue-500" />
                        {formatLocalTime(item.date)}
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex flex-col">
                        <span className="font-extrabold text-slate-900 tracking-tight group-hover:text-blue-600 transition-colors uppercase line-clamp-1">{item.title}</span>
                        <span className="text-[9px] text-slate-500 font-bold tracking-tighter opacity-80 italic">{item.clientName || 'Consumidor Final'}</span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className="bg-slate-100 px-2.5 py-1 rounded-md text-[8px] font-black text-slate-700 uppercase tracking-tighter border border-slate-200">
                        {item.category}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right font-black text-slate-950 text-sm">
                      <span className="text-[10px] opacity-40 mr-1">$</span>
                      {formatCurrency(item.amount)}
                    </td>
                  </motion.tr>
                ))}
              </AnimatePresence>
            </tbody>
          </table>
        </div>

        {/* Footer Dark Bar (Más compacta y alto contraste) */}
        <div className="px-6 py-4 bg-slate-900 border-t border-slate-800 flex justify-between items-center shadow-[0_-10px_30px_rgba(0,0,0,0.15)] flex-shrink-0">
          <div className="flex items-center gap-8">
            <SummaryItem icon={<Banknote size={14} />} label="Efectivo" value={formatCurrency(data?.totalCash || 0)} color="text-emerald-400" />
            <SummaryItem icon={<CreditCard size={14} />} label="Tarjetas" value={formatCurrency((data?.totalDebit || 0) + (data?.totalCredit || 0))} color="text-blue-400" />
            <SummaryItem icon={<ArrowRightLeft size={14} />} label="Transf." value={formatCurrency(data?.totalTransfer || 0)} color="text-indigo-400" />
          </div>

          <div className="flex flex-col items-end">
            <span className="text-[8px] font-black text-blue-500 uppercase tracking-[0.2em] mb-0.5">Cierre Parcial</span>
            <div className="text-xl font-mono font-black text-white flex items-baseline gap-1.5">
              <span className="text-[9px] font-sans font-bold text-white/30 uppercase tracking-widest">TOTAL</span>
              <span className="text-green-400">$ {formatCurrency(data?.totalRevenue || 0)}</span>
            </div>
          </div>
        </div>
      </div>

      {showClosingModal && (
        <CashClosingModal onClose={() => setShowClosingModal(false)} onComplete={handleClosingComplete} />
      )}
    </div>
  );
}

function KPICard({ icon, label, value, badge, color }: any) {
  const colorStyles: any = {
    emerald: "bg-emerald-500/10 text-emerald-600",
    blue: "bg-blue-500/10 text-blue-600"
  };

  return (
    <motion.div whileHover={{ y: -3 }} className="bg-white p-4 rounded-[1.5rem] shadow-lg border border-slate-100 flex flex-col justify-between">
      <div className="flex justify-between items-start mb-2">
        <div className={`p-2 rounded-xl ${colorStyles[color]}`}>{icon}</div>
        <span className={`text-[8px] font-black px-2 py-0.5 rounded-md uppercase tracking-widest ${colorStyles[color]}`}>{badge}</span>
      </div>
      <div>
        <div className="text-slate-600 text-[8px] font-black uppercase tracking-widest mb-0.5">{label}</div>
        <div className="text-2xl font-mono font-black text-slate-950 leading-none">
          {value}
        </div>
      </div>
    </motion.div>
  );
}

function SummaryItem({ icon, label, value, color }: any) {
  return (
    <div className="flex items-center gap-2.5">
      <div className={`p-1.5 bg-white/5 rounded-lg ${color}`}>{icon}</div>
      <div className="flex flex-col leading-tight">
        <span className="text-[7px] font-black text-slate-500 uppercase tracking-tighter">{label}</span>
        <span className="text-xs font-mono font-bold text-white tracking-tighter">$ {value}</span>
      </div>
    </div>
  );
}