"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import {
  Badge,
  Box,
  Button,
  Group,
  SegmentedControl,
  Select,
  SimpleGrid,
  Stack,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import { useQuery } from "@tanstack/react-query";
import { HelpDeskAdminLayout } from "@/layouts/HelpDeskAdminLayout";
import { TicketPriorityBadge, TicketStatusBadge } from "@/components/help-desk-admin/TicketBadges";
import { categoryLabels, ticketPriorityOptions, ticketStatusOptions } from "@/config/helpDeskAdminNav";
import { helpDeskAdminService } from "@/services/helpDeskAdminService";
import { useAuthStore } from "@/store/authStore";
import type { TicketViewMode } from "@/types/helpDeskAdmin";

export default function AdminTicketsPage() {
  const token = useAuthStore((s) => s.token)!;
  const [view, setView] = useState<TicketViewMode>("table");
  const [search, setSearch] = useState("");
  const [status, setStatus] = useState<string | null>(null);
  const [priority, setPriority] = useState<string | null>(null);

  const { data, isLoading } = useQuery({
    queryKey: ["hd-tickets", status, priority, search],
    queryFn: () =>
      helpDeskAdminService.listTickets(token, {
        status: status ?? undefined,
        priority: priority ?? undefined,
        search: search || undefined,
        per_page: 50,
      }),
    refetchInterval: 15000,
  });

  const tickets = data?.data ?? [];

  const kanbanColumns = useMemo(() => {
    return ticketStatusOptions.map((col) => ({
      ...col,
      items: tickets.filter((t) => t.status === col.value),
    }));
  }, [tickets]);

  return (
    <HelpDeskAdminLayout
      title="Central de atendimento"
      subtitle="Gerencie tickets em tempo real"
      search={search}
      onSearchChange={setSearch}
      searchPlaceholder="Buscar por assunto, cliente, e-mail..."
    >
      <Stack gap="lg">
        <Group justify="space-between" wrap="wrap">
          <Group gap="sm">
            <Select
              placeholder="Status"
              clearable
              data={ticketStatusOptions.map((s) => ({ value: s.value, label: s.label }))}
              value={status}
              onChange={setStatus}
              w={160}
            />
            <Select
              placeholder="Prioridade"
              clearable
              data={ticketPriorityOptions.map((p) => ({ value: p.value, label: p.label }))}
              value={priority}
              onChange={setPriority}
              w={160}
            />
          </Group>
          <SegmentedControl
            value={view}
            onChange={(v) => setView(v as TicketViewMode)}
            data={[
              { label: "Tabela", value: "table" },
              { label: "Kanban", value: "kanban" },
              { label: "Inbox", value: "inbox" },
            ]}
          />
        </Group>

        {isLoading && <Text c="dimmed">Carregando tickets...</Text>}

        {!isLoading && view === "table" && (
          <Box style={{ overflowX: "auto", borderRadius: 14, border: "1px solid rgba(0,155,255,0.12)" }}>
            <Table highlightOnHover striped>
              <Table.Thead>
                <Table.Tr>
                  <Table.Th>#</Table.Th>
                  <Table.Th>Cliente</Table.Th>
                  <Table.Th>Assunto</Table.Th>
                  <Table.Th>Categoria</Table.Th>
                  <Table.Th>Status</Table.Th>
                  <Table.Th>Prioridade</Table.Th>
                  <Table.Th>Atualizado</Table.Th>
                  <Table.Th />
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {tickets.map((t) => (
                  <Table.Tr key={t.id}>
                    <Table.Td>{t.id}</Table.Td>
                    <Table.Td>
                      <Text size="sm" fw={600}>
                        {t.name}
                      </Text>
                      <Text size="xs" c="dimmed">
                        {t.email}
                      </Text>
                    </Table.Td>
                    <Table.Td>{t.subject}</Table.Td>
                    <Table.Td>{categoryLabels[t.ticketCategory ?? ""] ?? t.ticketCategory ?? "—"}</Table.Td>
                    <Table.Td>
                      <TicketStatusBadge status={t.status} />
                    </Table.Td>
                    <Table.Td>
                      <TicketPriorityBadge priority={t.priority} />
                    </Table.Td>
                    <Table.Td>{t.updatedAt ? new Date(t.updatedAt).toLocaleString("pt-BR") : "—"}</Table.Td>
                    <Table.Td>
                      <Button component={Link} href={`/dashboard/central-ajuda/tickets/${t.id}`} size="xs" variant="light">
                        Abrir
                      </Button>
                    </Table.Td>
                  </Table.Tr>
                ))}
              </Table.Tbody>
            </Table>
          </Box>
        )}

        {!isLoading && view === "kanban" && (
          <SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="md">
            {kanbanColumns.map((col) => (
              <Box
                key={col.value}
                p="md"
                style={{
                  borderRadius: 14,
                  background: "rgba(255,255,255,0.02)",
                  border: "1px solid rgba(0,155,255,0.1)",
                  minHeight: 320,
                }}
              >
                <Group justify="space-between" mb="md">
                  <Text fw={700}>
                    {col.label}
                  </Text>
                  <Badge>{col.items.length}</Badge>
                </Group>
                <Stack gap="sm">
                  {col.items.map((t) => (
                    <Box
                      key={t.id}
                      component={Link}
                      href={`/dashboard/central-ajuda/tickets/${t.id}`}
                      p="sm"
                      style={{
                        borderRadius: 12,
                        background: "rgba(255,255,255,0.04)",
                        border: "1px solid rgba(255,255,255,0.06)",
                        textDecoration: "none",
                        color: "inherit",
                      }}
                    >
                      <Text size="sm" fw={700} lineClamp={2}>
                        {t.subject}
                      </Text>
                      <Text size="xs" c="dimmed" mt={4}>
                        {t.name}
                      </Text>
                    </Box>
                  ))}
                </Stack>
              </Box>
            ))}
          </SimpleGrid>
        )}

        {!isLoading && view === "inbox" && (
          <SimpleGrid cols={{ base: 1, md: 2 }} spacing="md">
            {tickets.map((t) => (
              <Box
                key={t.id}
                component={Link}
                href={`/dashboard/central-ajuda/tickets/${t.id}`}
                p="lg"
                style={{
                  borderRadius: 16,
                  background: "rgba(255,255,255,0.03)",
                  border: "1px solid rgba(0,155,255,0.12)",
                  textDecoration: "none",
                  color: "inherit",
                }}
              >
                <Group justify="space-between" mb="xs">
                  <Text fw={800}>
                    {t.name}
                  </Text>
                  <TicketStatusBadge status={t.status} />
                </Group>
                <Text size="sm" mb={4}>
                  {t.subject}
                </Text>
                <Text size="xs" c="dimmed" lineClamp={2}>
                  {t.message}
                </Text>
              </Box>
            ))}
          </SimpleGrid>
        )}
      </Stack>
    </HelpDeskAdminLayout>
  );
}
