"use client";

import { Box, Button, Group, Stack, Table, Text, TextInput } from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { HelpDeskAdminLayout } from "@/layouts/HelpDeskAdminLayout";
import { helpDeskAdminService } from "@/services/helpDeskAdminService";
import { useAuthStore } from "@/store/authStore";
import { useState } from "react";

export default function AdminClientsPage() {
  const token = useAuthStore((s) => s.token)!;
  const [search, setSearch] = useState("");

  const { data, isLoading } = useQuery({
    queryKey: ["hd-clients", search],
    queryFn: () => helpDeskAdminService.listClients(token, search || undefined),
  });

  const clients = data?.data ?? [];

  return (
    <HelpDeskAdminLayout title="Clientes" subtitle="Central de clientes e histórico">
      <Stack gap="lg">
        <Group>
          <TextInput placeholder="Buscar por nome, e-mail ou empresa..." value={search} onChange={(e) => setSearch(e.currentTarget.value)} style={{ flex: 1 }} />
          <Button variant="light">Novo cliente</Button>
        </Group>
        {isLoading ? (
          <Text c="dimmed">Carregando...</Text>
        ) : (
          <Box className="hd-panel" style={{ overflowX: "auto" }}>
            <Table>
              <Table.Thead>
                <Table.Tr>
                  <Table.Th>Nome</Table.Th>
                  <Table.Th>E-mail</Table.Th>
                  <Table.Th>Empresa</Table.Th>
                  <Table.Th>Tickets</Table.Th>
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {clients.map((c) => (
                  <Table.Tr key={c.id}>
                    <Table.Td>{c.name}</Table.Td>
                    <Table.Td>{c.email}</Table.Td>
                    <Table.Td>{c.company ?? "—"}</Table.Td>
                    <Table.Td>{c.tickets_count}</Table.Td>
                  </Table.Tr>
                ))}
              </Table.Tbody>
            </Table>
          </Box>
        )}
      </Stack>
    </HelpDeskAdminLayout>
  );
}
