'use client';

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

type OrderItem = {
  id: string;
  status: string;
  total: number | string;
  notes?: string | null;
  createdAt: string;
  customer: { fullName: string };
  address?: {
    street?: string | null;
    number?: string | null;
    neighborhood?: string | null;
    city?: string | null;
  } | null;
  payment?: { status?: string | null; method?: string | null } | null;
  delivery?: {
    id: string;
    status: string;
    etaMinutes?: number | null;
    driver?: {
      fullName?: string | null;
      vehiclePlate?: string | null;
      vehicleModel?: string | null;
    } | null;
  } | null;
  items: Array<{
    id: string;
    quantity: number;
    notes?: string | null;
    totalPrice: number | string;
    product?: { name?: string | null } | null;
  }>;
};

const labels: Record<string, string> = {
  SENT_TO_RESTAURANT: 'Aguardando aceite',
  PREPARING: 'Em preparo',
  READY_FOR_PICKUP: 'Pronto',
  SEARCHING_DRIVER: 'Buscando motoboy',
  DRIVER_ACCEPTED: 'Motoboy a caminho',
  DRIVER_ARRIVED: 'Motoboy chegou',
  PICKED_UP: 'Pedido retirado',
  ON_THE_WAY: 'Saiu para entrega',
  DELIVERED: 'Entregue',
  CANCELLED: 'Cancelado',
  PAID: 'Pago',
  PENDING: 'Pendente',
  ASSIGNED: 'Oferta enviada',
  ACCEPTED: 'Corrida aceita',
};

function label(status?: string | null) {
  return labels[status ?? ''] ?? (status ?? 'Sem status').replaceAll('_', ' ');
}

function tone(status?: string | null) {
  switch (status) {
    case 'DELIVERED':
    case 'PAID':
      return 'emerald';
    case 'SENT_TO_RESTAURANT':
    case 'READY_FOR_PICKUP':
    case 'ASSIGNED':
      return 'amber';
    case 'PREPARING':
    case 'SEARCHING_DRIVER':
    case 'DRIVER_ACCEPTED':
    case 'DRIVER_ARRIVED':
    case 'PICKED_UP':
    case 'ON_THE_WAY':
      return 'sky';
    case 'CANCELLED':
      return 'rose';
    default:
      return 'sky';
  }
}

function validationCode(orderId: string) {
  return orderId.slice(-6).toUpperCase();
}

function compactAddress(address?: OrderItem['address']) {
  if (!address) return 'Endereço não informado';
  return [address.street, address.number, address.neighborhood, address.city].filter(Boolean).join(', ');
}

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

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

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

  const metrics = useMemo(
    () => [
      { label: 'Aguardando', value: String(items.filter((item) => item.status === 'SENT_TO_RESTAURANT').length), hint: 'aceite da loja', tone: 'amber' as const },
      { label: 'Preparo', value: String(items.filter((item) => item.status === 'PREPARING').length), hint: 'cozinha rodando', tone: 'sky' as const },
      { label: 'Entrega', value: String(items.filter((item) => ['READY_FOR_PICKUP', 'SEARCHING_DRIVER', 'DRIVER_ACCEPTED', 'PICKED_UP', 'ON_THE_WAY'].includes(item.status)).length), hint: 'pronto ou em rota', tone: 'emerald' as const },
      { label: 'Concluídos', value: String(items.filter((item) => item.status === 'DELIVERED').length), hint: 'histórico da loja', tone: 'rose' as const },
    ],
    [items],
  );

  const runAction = async (orderId: string, action: 'accept' | 'ready' | 'request-delivery') => {
    const paths = {
      accept: '/accept',
      ready: '/ready',
      'request-delivery': '/request-delivery',
    } as const;

    setBusyOrderId(orderId);
    setError('');
    setSuccess('');
    try {
      await fetchWithSession(`/orders/${orderId}${paths[action]}`, { method: 'PATCH' });
      setSuccess(
        action === 'accept'
          ? 'Pedido aceito e enviado para preparo.'
          : action === 'ready'
            ? 'Pedido marcado como pronto para retirada.'
            : 'Solicitação enviada para os motoboys ativos e online.',
      );
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Falha ao executar ação do pedido.');
    } finally {
      setBusyOrderId('');
    }
  };

  return (
    <div className="space-y-6">
      <section className="grid gap-4 md:grid-cols-4">
        {metrics.map((metric) => <StatCard key={metric.label} {...metric} />)}
      </section>

      <Panel
        title="Pedidos da loja"
        eyebrow="Fila operacional"
        action={
          <button
            type="button"
            onClick={() => void load()}
            className="rounded-full border border-slate-200 bg-white px-4 py-2 text-[11px] font-black uppercase tracking-[0.18em] text-slate-700"
          >
            Atualizar
          </button>
        }
      >
        {error ? <p className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{error}</p> : null}
        {success ? <p className="rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">{success}</p> : null}

        <div className="mt-5 space-y-4">
          {loading ? <p className="text-sm text-slate-500">Carregando pedidos...</p> : null}
          {!loading && !items.length ? <p className="text-sm text-slate-500">Nenhum pedido na fila desta loja.</p> : null}

          {items.map((item) => {
            const canAccept = item.status === 'SENT_TO_RESTAURANT';
            const canReady = item.status === 'PREPARING';
            const canRequestDelivery = item.status === 'READY_FOR_PICKUP' || item.status === 'SEARCHING_DRIVER';
            const code = validationCode(item.id);

            return (
              <article key={item.id} className="rounded-[1.6rem] border border-slate-200 bg-white p-5 shadow-[0_16px_42px_rgba(15,23,42,0.06)]">
                <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                  <div>
                    <div className="flex flex-wrap items-center gap-3">
                      <h3 className="text-lg font-black text-slate-950">Pedido {item.id.slice(0, 8)}</h3>
                      <StatusBadge tone={tone(item.status)}>{label(item.status)}</StatusBadge>
                      <StatusBadge tone={tone(item.payment?.status)}>{label(item.payment?.status)}</StatusBadge>
                    </div>
                    <p className="mt-2 text-sm text-slate-600">
                      {item.customer.fullName} • {new Date(item.createdAt).toLocaleString('pt-BR')}
                    </p>
                    <p className="mt-1 text-sm text-slate-600">{compactAddress(item.address)}</p>
                    <p className="mt-2 text-sm font-semibold text-slate-900">{currency(item.total)}</p>
                  </div>

                  <div className="min-w-[260px] rounded-[1.25rem] border border-slate-200 bg-slate-50 p-4">
                    <p className="text-[11px] font-black uppercase tracking-[0.24em] text-slate-500">Entrega</p>
                    <p className="mt-2 text-sm font-bold text-slate-900">
                      {item.delivery?.driver?.fullName ? item.delivery.driver.fullName : 'Aguardando motoboy'}
                    </p>
                    <p className="mt-1 text-sm text-slate-600">
                      {item.delivery?.driver
                        ? `${item.delivery.driver.vehicleModel ?? 'Veículo'}${item.delivery.driver.vehiclePlate ? ` • ${item.delivery.driver.vehiclePlate}` : ''}`
                        : 'Sem motoboy definido ainda'}
                    </p>
                    <p className="mt-1 text-sm text-slate-600">ETA: <strong>{item.delivery?.etaMinutes ?? '--'} min</strong></p>
                    {(item.status === 'DRIVER_ACCEPTED' || item.status === 'DRIVER_ARRIVED' || item.status === 'PICKED_UP' || item.status === 'ON_THE_WAY') ? (
                      <div className="mt-3 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3">
                        <p className="text-[11px] font-black uppercase tracking-[0.24em] text-emerald-700">Código de validação</p>
                        <p className="mt-2 text-2xl font-black tracking-[0.2em] text-emerald-900">{code}</p>
                        <p className="mt-2 text-xs leading-5 text-emerald-700">Informe este código para validar a retirada do pedido pelo motoboy.</p>
                      </div>
                    ) : null}
                  </div>
                </div>

                <div className="mt-4 rounded-[1.25rem] border border-slate-200 bg-slate-50 p-4">
                  <p className="text-[11px] font-black uppercase tracking-[0.24em] text-slate-500">Itens</p>
                  <div className="mt-3 space-y-2">
                    {item.items.map((orderItem) => (
                      <div key={orderItem.id} className="flex items-center justify-between gap-3 rounded-2xl bg-white px-4 py-3 text-sm text-slate-700">
                        <div>
                          <strong className="text-slate-900">{orderItem.quantity}x {orderItem.product?.name ?? 'Produto'}</strong>
                          {orderItem.notes ? <p className="mt-1 text-xs text-slate-500">Obs.: {orderItem.notes}</p> : null}
                        </div>
                        <span>{currency(orderItem.totalPrice)}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="mt-4 flex flex-wrap gap-3">
                  <button
                    type="button"
                    disabled={!canAccept || busyOrderId === item.id}
                    onClick={() => void runAction(item.id, 'accept')}
                    className="h-11 rounded-2xl bg-[#ff7a1a] px-4 text-sm font-black text-[#10141b] disabled:cursor-not-allowed disabled:opacity-40"
                  >
                    Aceitar
                  </button>
                  <button
                    type="button"
                    disabled={!canReady || busyOrderId === item.id}
                    onClick={() => void runAction(item.id, 'ready')}
                    className="h-11 rounded-2xl bg-[#0f172a] px-4 text-sm font-black text-white disabled:cursor-not-allowed disabled:opacity-40"
                  >
                    Pedido pronto
                  </button>
                  <button
                    type="button"
                    disabled={!canRequestDelivery || busyOrderId === item.id}
                    onClick={() => void runAction(item.id, 'request-delivery')}
                    className="h-11 rounded-2xl border border-emerald-300 bg-emerald-50 px-4 text-sm font-black text-emerald-800 disabled:cursor-not-allowed disabled:opacity-40"
                  >
                    Solicitar entrega
                  </button>
                </div>
              </article>
            );
          })}
        </div>
      </Panel>
    </div>
  );
}
