"use client";

import { Box, Button, Stack, Text, TextInput, Textarea } from "@mantine/core";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { notifications } from "@mantine/notifications";
import { HelpDeskAdminLayout } from "@/layouts/HelpDeskAdminLayout";
import { helpDeskAdminService } from "@/services/helpDeskAdminService";
import { useAuthStore } from "@/store/authStore";
import { useState } from "react";

export default function AdminSettingsPage() {
  const token = useAuthStore((s) => s.token)!;
  const qc = useQueryClient();
  const [companyName, setCompanyName] = useState("NOGA CODE");

  const { data } = useQuery({
    queryKey: ["hd-settings"],
    queryFn: () => helpDeskAdminService.getSettings(token).then((r) => r.data),
  });

  const save = useMutation({
    mutationFn: () =>
      helpDeskAdminService.saveSettings(token, {
        company: { name: companyName, logo: "/assets/logo_nogacode_az.png" },
        sla: { first_response_hours: 4, resolution_hours: 48 },
      }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["hd-settings"] });
      notifications.show({ message: "Configurações salvas", color: "green" });
    },
  });

  return (
    <HelpDeskAdminLayout title="Configurações" subtitle="Empresa, SLA, categorias e integrações">
      <Stack gap="lg" maw={720}>
        <Box className="hd-panel" p="lg">
          <Text fw={800} mb="md">
            Empresa
          </Text>
          <TextInput label="Nome" value={companyName} onChange={(e) => setCompanyName(e.currentTarget.value)} />
          <TextInput label="Logo (URL)" mt="sm" defaultValue="/assets/logo_nogacode_az.png" />
        </Box>
        <Box className="hd-panel" p="lg">
          <Text fw={800} mb="md">
            SLA
          </Text>
          <TextInput label="Primeira resposta (horas)" defaultValue="4" />
          <TextInput label="Resolução (horas)" mt="sm" defaultValue="48" />
        </Box>
        <Box className="hd-panel" p="lg">
          <Text fw={800} mb="md">
            Horário de atendimento
          </Text>
          <Textarea label="Dias úteis" defaultValue="Seg–Sex, 09:00–18:00 (America/Sao_Paulo)" minRows={2} />
        </Box>
        <Box className="hd-panel" p="lg">
          <Text fw={800} mb="md">
            Tags disponíveis
          </Text>
          <Stack gap="xs">
            {(data?.tags ?? []).map((t) => (
              <Text key={t.id} size="sm">
                <Text span fw={700} style={{ color: t.color }}>
                  ●
                </Text>{" "}
                {t.name}
              </Text>
            ))}
          </Stack>
        </Box>
        <Button onClick={() => save.mutate()} loading={save.isPending}>
          Salvar configurações
        </Button>
      </Stack>
    </HelpDeskAdminLayout>
  );
}
