"use client";

import { Alert, Loader, Stack } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { DashboardPage } from "@/components/dashboard/DashboardPage";
import { PageHeader } from "@/components/dashboard/PageHeader";
import { DataTable } from "@/components/dashboard/DataTable";
import { adminDashboardService } from "@/services/adminDashboardService";
import { useAuthStore } from "@/store/authStore";

export default function PedidosPage() {
  const token = useAuthStore((s) => s.token);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["admin-dashboard-overview"],
    queryFn: () => adminDashboardService.overview(token!),
    enabled: Boolean(token),
    select: (r) => r.data?.recentQuotes ?? [],
  });

  const rows =
    data?.map((q) => ({
      id: `#PLN-${q.id}`,
      client: q.client,
      tipo: q.tipo,
      status: q.status,
      value: q.value,
    })) ?? [];

  return (
    <DashboardPage title="Pedidos">
      <PageHeader
        title="Planejamentos"
        description="Propostas de planejamento enviadas pelos clientes (dados reais da API)."
      />
      {isError && (
        <Alert color="red" mb="md">
          Não foi possível carregar.{" "}
          <button type="button" onClick={() => refetch()}>
            Tentar novamente
          </button>
        </Alert>
      )}
      {isLoading ? (
        <Stack align="center" py="xl">
          <Loader color="blue" />
        </Stack>
      ) : (
        <DataTable
          columns={[
            { key: "id", label: "ID" },
            { key: "client", label: "Cliente" },
            { key: "tipo", label: "Tipo" },
            { key: "status", label: "Status" },
            { key: "value", label: "Valor" },
          ]}
          data={rows}
          emptyMessage="Nenhum planejamento registrado ainda."
        />
      )}
    </DashboardPage>
  );
}
