"use client";

import { Box, Button, Group, SimpleGrid, Stack, Text } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { Download, FileSpreadsheet, FileText } from "lucide-react";
import { HelpDeskAdminLayout } from "@/layouts/HelpDeskAdminLayout";
import { downloadCsv } from "@/lib/exportCsv";
import { helpDeskAdminService } from "@/services/helpDeskAdminService";
import { useAuthStore } from "@/store/authStore";

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

  const exportTickets = async (format: "csv" | "excel") => {
    try {
      const res = await helpDeskAdminService.listTickets(token, { per_page: 500 });
      const tickets = res.data ?? [];
      const rows = [
        ["ID", "Cliente", "E-mail", "Assunto", "Status", "Prioridade", "Categoria", "Criado em"],
        ...tickets.map((t) => [
          String(t.id),
          t.name ?? "",
          t.email ?? "",
          t.subject,
          t.status,
          t.priority,
          t.ticketCategory ?? "",
          t.createdAt ? new Date(t.createdAt).toLocaleString("pt-BR") : "",
        ]),
      ];
      const ext = format === "excel" ? "xls" : "csv";
      downloadCsv(`tickets-${new Date().toISOString().slice(0, 10)}.${ext}`, rows);
      notifications.show({ message: "Exportação concluída", color: "green" });
    } catch {
      notifications.show({ message: "Erro ao exportar tickets", color: "red" });
    }
  };

  const exportClients = async () => {
    try {
      const res = await helpDeskAdminService.listClients(token);
      const clients = res.data ?? [];
      downloadCsv(`clientes-${new Date().toISOString().slice(0, 10)}.csv`, [
        ["ID", "Nome", "E-mail", "Empresa", "Tickets"],
        ...clients.map((c) => [String(c.id), c.name, c.email, c.company ?? "", String(c.tickets_count)]),
      ]);
      notifications.show({ message: "Clientes exportados", color: "green" });
    } catch {
      notifications.show({ message: "Erro ao exportar clientes", color: "red" });
    }
  };

  const exportSla = async () => {
    try {
      const res = await helpDeskAdminService.dashboard(token);
      const d = res.data;
      downloadCsv(`sla-${new Date().toISOString().slice(0, 10)}.csv`, [
        ["Métrica", "Valor"],
        ["Tickets abertos", String(d?.ticketsOpen ?? 0)],
        ["Em andamento", String(d?.ticketsInProgress ?? 0)],
        ["Resolvidos", String(d?.ticketsResolved ?? 0)],
        ["SLA estourado", String(d?.slaBreached ?? 0)],
        ["Tempo médio resposta (min)", String(d?.avgResponseMinutes ?? "—")],
      ]);
      notifications.show({ message: "Relatório SLA exportado", color: "green" });
    } catch {
      notifications.show({ message: "Erro ao exportar SLA", color: "red" });
    }
  };

  const cards = [
    {
      title: "Tickets",
      desc: "Exportar todos os tickets do período",
      icon: FileText,
      actions: [
        { label: "CSV", onClick: () => exportTickets("csv") },
        { label: "Excel", onClick: () => exportTickets("excel") },
      ],
    },
    {
      title: "SLA",
      desc: "Tempo de resposta e violações",
      icon: FileSpreadsheet,
      actions: [{ label: "CSV", onClick: exportSla }],
    },
    {
      title: "Clientes",
      desc: "Histórico por cliente",
      icon: Download,
      actions: [{ label: "CSV", onClick: exportClients }],
    },
  ];

  return (
    <HelpDeskAdminLayout title="Relatórios" subtitle="Exportação e performance">
      <SimpleGrid cols={{ base: 1, md: 3 }} spacing="md">
        {cards.map(({ title, desc, icon: Icon, actions }) => (
          <Box key={title} className="hd-panel" p="xl">
            <Icon size={28} color="#009bff" />
            <Text fw={800} mt="md">
              {title}
            </Text>
            <Text size="sm" c="dimmed" mt={4} mb="lg">
              {desc}
            </Text>
            <Group gap="xs">
              {actions.map((a) => (
                <Button key={a.label} size="xs" variant="light" onClick={a.onClick}>
                  {a.label}
                </Button>
              ))}
            </Group>
          </Box>
        ))}
      </SimpleGrid>
      <Stack mt="xl" gap="sm">
        <Text c="dimmed" size="sm">
          Exportações PDF serão adicionadas na próxima iteração. CSV e Excel (compatível) já funcionam com dados reais da API.
        </Text>
      </Stack>
    </HelpDeskAdminLayout>
  );
}
