"use client";

import { Alert, Loader, Stack, Text } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { DashboardPage } from "@/components/dashboard/DashboardPage";
import { PageHeader } from "@/components/dashboard/PageHeader";
import { GlassCard } from "@/components/ui/GlassCard";
import { helpDeskAdminService } from "@/services/helpDeskAdminService";
import { useAuthStore } from "@/store/authStore";
import { useBrandColors } from "@/hooks/useBrandColors";

export default function NotificacoesPage() {
  const token = useAuthStore((s) => s.token);
  const c = useBrandColors();

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["hd-dashboard-activity"],
    queryFn: () => helpDeskAdminService.dashboard(token!),
    enabled: Boolean(token),
    select: (r) => r.data?.recentActivity ?? [],
  });

  const items = data ?? [];

  return (
    <DashboardPage title="Notificações">
      <PageHeader title="Atividade recente" description="Últimas ações registradas na central de ajuda." />
      {isError && (
        <Alert color="red" mb="md">
          Erro ao carregar.{" "}
          <button type="button" onClick={() => refetch()}>
            Tentar novamente
          </button>
        </Alert>
      )}
      {isLoading ? (
        <Stack align="center" py="xl">
          <Loader color="blue" />
        </Stack>
      ) : items.length === 0 ? (
        <Alert color="blue">Nenhuma atividade registrada ainda.</Alert>
      ) : (
        <Stack gap="sm">
          {items.map((log) => (
            <GlassCard key={log.id} p="md" hover={false}>
              <Text fw={600} style={{ color: c.heading }}>
                {log.user?.name ?? "Sistema"} — {log.action}
              </Text>
              <Text size="xs" style={{ color: c.muted }}>
                {log.entity_type ? `${log.entity_type} #${log.entity_id}` : ""}
                {log.created_at
                  ? ` · ${new Date(log.created_at).toLocaleString("pt-BR")}`
                  : ""}
              </Text>
            </GlassCard>
          ))}
        </Stack>
      )}
    </DashboardPage>
  );
}
