'use client';

import { CrudToolbar, ManagementTable, Panel, StatCard } from '@chego/ui';
import { useEffect, useMemo, useState } from 'react';
import { currency, fetchWithSession, humanStatus, statusTone } from './api-helpers';

type OrderItem = {
  id: string;
  status: string;
  total: number | string;
  createdAt: string;
  notes?: string | null;
  customer: { fullName: string };
  restaurant: { name: string };
  payment?: { status?: string | null };
};

export function OrdersLivePanel() {
  const [items, setItems] = useState<OrderItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = async () => {
    setLoading(true);
    setError('');
    try {
      setItems(await fetchWithSession('/orders'));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Falha ao carregar pedidos.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
    const intervalId = window.setInterval(() => {
      void load();
    }, 10000);
    return () => window.clearInterval(intervalId);
  }, []);

  const metrics = useMemo(() => [
    { label: 'Pedidos ativos', value: String(items.filter((item) => !['DELIVERED', 'CANCELLED'].includes(item.status)).length), hint: 'monitorados em tempo real', tone: 'amber' as const },
    { label: 'Cancelados', value: String(items.filter((item) => item.status === 'CANCELLED').length), hint: 'com log e motivo', tone: 'rose' as const },
    { label: 'Pagos', value: String(items.filter((item) => item.payment?.status === 'PAID').length), hint: 'pedidos conciliados', tone: 'emerald' as const },
    { label: 'Total', value: String(items.length), hint: 'escopo administrativo', tone: 'sky' as const },
  ], [items]);

  const cancelOrder = async (item: OrderItem) => {
    if (!window.confirm(`Cancelar o pedido ${item.id}?`)) return;
    await fetchWithSession(`/orders/${item.id}/cancel`, {
      method: 'PATCH',
      body: JSON.stringify({ reason: 'Cancelamento administrativo pelo painel.' }),
    });
    await load();
  };

  return (
    <>
      <section className="grid gap-4 md:grid-cols-4">
        {metrics.map((metric) => <StatCard key={metric.label} {...metric} />)}
      </section>
      <Panel title="Gestao de pedidos" eyebrow="Centro operacional em tempo real">
        <CrudToolbar filters={['dados remotos', 'escopo por papel', 'cancelamento auditavel']} actions={[{ label: 'Atualizar painel', tone: 'neutral', href: '#' }]} />
        {error ? <p className="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{error}</p> : null}
        <div className="mt-5">
          <ManagementTable
            columns={[
              { key: 'order', label: 'Pedido' },
              { key: 'customer', label: 'Cliente' },
              { key: 'store', label: 'Loja' },
              { key: 'total', label: 'Total', align: 'right' },
              { key: 'payment', label: 'Pagamento' },
              { key: 'status', label: 'Status' },
            ]}
            rows={items.map((item) => ({
              id: item.id,
              cells: {
                order: <div><p className="font-bold text-slate-900">{item.id}</p><p className="text-xs text-slate-500">{new Date(item.createdAt).toLocaleString('pt-BR')}</p></div>,
                customer: item.customer.fullName,
                store: item.restaurant.name,
                total: <span className="font-semibold text-slate-900">{currency(item.total)}</span>,
                payment: { value: humanStatus(item.payment?.status ?? 'PENDING'), tone: statusTone(item.payment?.status), badge: true },
                status: { value: humanStatus(item.status), tone: statusTone(item.status), badge: true },
              },
            }))}
            pageLabel={loading ? 'Carregando pedidos...' : `Mostrando ${items.length} pedidos sincronizados`}
            getRowActions={(row) => {
              const item = items.find((entry) => entry.id === row.id);
              if (!item) return [];
              return [
                { label: 'Cancelar', onClick: () => void cancelOrder(item) },
              ];
            }}
          />
        </div>
      </Panel>
    </>
  );
}
