"use client";

import { Loader, Switch, Table, Text } from "@mantine/core";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { DashboardPage } from "@/components/dashboard/DashboardPage";
import { PageHeader } from "@/components/dashboard/PageHeader";
import { adminAppCreationService } from "@/services/adminAppCreationService";
import { useAuthStore } from "@/store/authStore";
import { formatCurrency } from "@/utils/format";

export default function CriacaoAppOpcionaisPage() {
  const token = useAuthStore((s) => s.token);
  const queryClient = useQueryClient();

  const { data, isLoading } = useQuery({
    queryKey: ["admin", "app-creation", "optionals"],
    queryFn: () => adminAppCreationService.optionals.list(token!),
    enabled: Boolean(token),
  });

  const optionals = data?.data ?? [];

  const toggleMutation = useMutation({
    mutationFn: (id: number) => adminAppCreationService.optionals.toggle(token!, id),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["admin", "app-creation", "optionals"] }),
  });

  return (
    <DashboardPage title="Opcionais">
      <PageHeader
        title="Opcionais de criação do app"
        description={`${optionals.length} itens — totalmente editáveis, sem hardcode.`}
      />
      {isLoading ? (
        <Loader />
      ) : (
        <Table striped highlightOnHover withTableBorder>
          <Table.Thead>
            <Table.Tr>
              <Table.Th>Nome</Table.Th>
              <Table.Th>Categoria</Table.Th>
              <Table.Th>Preço</Table.Th>
              <Table.Th>Ativo</Table.Th>
            </Table.Tr>
          </Table.Thead>
          <Table.Tbody>
            {optionals.map((o) => (
              <Table.Tr key={o.id}>
                <Table.Td>
                  <Text size="sm" fw={500}>
                    {o.name}
                  </Text>
                </Table.Td>
                <Table.Td>{o.categorySlug ?? "—"}</Table.Td>
                <Table.Td>
                  {o.recurring
                    ? `${formatCurrency(o.monthlyPrice ?? o.price)}/mês`
                    : formatCurrency(o.price)}
                </Table.Td>
                <Table.Td>
                  <Switch
                    checked={o.active}
                    onChange={() => toggleMutation.mutate(o.id)}
                  />
                </Table.Td>
              </Table.Tr>
            ))}
          </Table.Tbody>
        </Table>
      )}
    </DashboardPage>
  );
}
