import { useState, useEffect } from 'react';
import { OrderService } from '../services/api';
import { RefreshCw, ShoppingCart, CheckCircle2, XCircle, Clock, AlertCircle } from 'lucide-react';

const STATUS_OPTIONS = [
  { value: '', label: 'Todos', color: 'text-slate-400', bg: 'bg-slate-800' },
  { value: 'pending', label: 'Pendente', color: 'text-yellow-400', bg: 'bg-yellow-400/10' },
  { value: 'paid', label: 'Pago', color: 'text-emerald-400', bg: 'bg-emerald-400/10' },
  { value: 'canceled', label: 'Cancelado', color: 'text-rose-400', bg: 'bg-rose-400/10' },
  { value: 'expired', label: 'Expirado', color: 'text-slate-500', bg: 'bg-slate-700/40' },
];

function StatusBadge({ status }: { status: string }) {
  const opt = STATUS_OPTIONS.find(s => s.value === status) ?? STATUS_OPTIONS[0];
  const icons: Record<string, JSX.Element> = {
    pending: <Clock size={12} />,
    paid: <CheckCircle2 size={12} />,
    canceled: <XCircle size={12} />,
    expired: <AlertCircle size={12} />,
  };
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest ${opt.color} ${opt.bg}`}>
      {icons[status] ?? null}
      {opt.label}
    </span>
  );
}

export default function OrdersPage() {
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState('');
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const params: any = {};
      if (statusFilter) params.status = statusFilter;
      if (fromDate) params.from = fromDate;
      if (toDate) params.to = toDate;
      const data = await OrderService.list(params);
      setOrders(data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { fetchOrders(); }, [statusFilter, fromDate, toDate]);

  const totals = orders.reduce((acc, o) => {
    acc[o.status] = (acc[o.status] || 0) + 1;
    if (o.status === 'paid') acc.revenue += parseFloat(o.total_amount || 0);
    return acc;
  }, { pending: 0, paid: 0, canceled: 0, expired: 0, revenue: 0 });

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header className="flex justify-between items-start">
        <div>
          <h2 className="text-3xl font-bold text-white">Pedidos & Pagamentos</h2>
          <p className="text-slate-400 mt-1">Histórico de transações e status de pagamentos.</p>
        </div>
        <button
          onClick={fetchOrders}
          className="p-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl transition-all border border-slate-700 active:rotate-180 duration-500"
        >
          <RefreshCw size={20} />
        </button>
      </header>

      {/* Summary cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Receita (pago)', value: `R$ ${totals.revenue.toFixed(2)}`, color: 'emerald' },
          { label: 'Pendentes', value: totals.pending, color: 'yellow' },
          { label: 'Cancelados', value: totals.canceled, color: 'rose' },
          { label: 'Expirados', value: totals.expired, color: 'slate' },
        ].map(c => (
          <div key={c.label} className="bg-slate-900/40 border border-slate-800 rounded-2xl p-5">
            <p className="text-slate-500 text-[10px] font-bold uppercase tracking-widest mb-1">{c.label}</p>
            <p className={`text-2xl font-black tabular-nums text-${c.color}-400`}>{c.value}</p>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex gap-2 flex-wrap">
          {STATUS_OPTIONS.map(opt => (
            <button
              key={opt.value}
              onClick={() => setStatusFilter(opt.value)}
              className={`px-4 py-2 rounded-xl text-xs font-bold uppercase tracking-wide transition-all border ${
                statusFilter === opt.value
                  ? `${opt.color} ${opt.bg} border-current`
                  : 'text-slate-500 bg-slate-900 border-slate-800 hover:border-slate-700'
              }`}
            >
              {opt.label}
            </button>
          ))}
        </div>
        <div className="ml-auto flex items-center gap-2">
          <input
            type="date"
            value={fromDate}
            onChange={e => setFromDate(e.target.value)}
            className="bg-slate-900 border border-slate-800 text-slate-300 text-xs rounded-xl px-3 py-2 focus:outline-none focus:border-cyan-500"
          />
          <span className="text-slate-600">→</span>
          <input
            type="date"
            value={toDate}
            onChange={e => setToDate(e.target.value)}
            className="bg-slate-900 border border-slate-800 text-slate-300 text-xs rounded-xl px-3 py-2 focus:outline-none focus:border-cyan-500"
          />
        </div>
      </div>

      {/* Table */}
      <div className="bg-slate-900/50 border border-slate-800 rounded-3xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="bg-slate-800/30 text-slate-500 text-[10px] uppercase tracking-widest font-bold">
                <th className="px-6 py-4">Referência</th>
                <th className="px-6 py-4">Status</th>
                <th className="px-6 py-4">Cliente</th>
                <th className="px-6 py-4">Tickets</th>
                <th className="px-6 py-4">Valor</th>
                <th className="px-6 py-4">Pagamento</th>
                <th className="px-6 py-4">Data</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-800">
              {loading ? (
                [1, 2, 3, 4].map(i => (
                  <tr key={i} className="animate-pulse">
                    <td colSpan={7} className="px-6 py-5 bg-slate-800/10" />
                  </tr>
                ))
              ) : orders.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-20 text-center text-slate-500">
                    <div className="flex flex-col items-center gap-3">
                      <ShoppingCart size={40} className="text-slate-800" />
                      <p>Nenhum pedido encontrado.</p>
                    </div>
                  </td>
                </tr>
              ) : orders.map(order => (
                <tr key={order.id} className="hover:bg-slate-800/20 transition-colors">
                  <td className="px-6 py-4" title={`ID completo: ${order.id}`}>
                    <span className="font-mono text-sm font-black text-white tracking-widest">
                      #{order.id.slice(-6).toUpperCase()}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <StatusBadge status={order.status} />
                  </td>
                  <td className="px-6 py-4">
                    <div className="text-sm font-bold text-white">{order.user_nome || '—'}</div>
                    <div className="text-[10px] text-slate-500 font-mono">{order.user_cpf}</div>
                  </td>
                  <td className="px-6 py-4 text-sm text-slate-300 tabular-nums font-bold">
                    {order.ticket_count ?? 0}
                  </td>
                  <td className="px-6 py-4 text-sm font-black text-emerald-400 tabular-nums">
                    R$ {parseFloat(order.total_amount || 0).toFixed(2)}
                  </td>
                  <td className="px-6 py-4">
                    <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">
                      {order.payment_method || 'PIX'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-[11px] text-slate-500 font-medium whitespace-nowrap tabular-nums">
                    {new Date(order.created_at).toLocaleString('pt-BR')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
