"use client";

import {
  Alert,
  Badge,
  Button,
  Group,
  Loader,
  NumberInput,
  PasswordInput,
  Select,
  Stack,
  Switch,
  Text,
  TextInput,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Mail, PlugZap, Save, Send } from "lucide-react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { DashboardPage } from "@/components/dashboard/DashboardPage";
import { PageHeader } from "@/components/dashboard/PageHeader";
import { GlassCard } from "@/components/ui/GlassCard";
import { PrimaryButton } from "@/components/ui/PrimaryButton";
import { adminMailService, type MailSettings } from "@/services/adminMailService";
import { useAuthStore } from "@/store/authStore";
import { colors } from "@/styles/tokens";

const defaultSettings: MailSettings = {
  enabled: true,
  from_name: "NOGA CODE",
  from_address: "",
  host: "",
  port: 465,
  username: "",
  password: "",
  encryption: "ssl",
  timeout: 30,
  reply_to: "",
  admin_email: "",
  password_reset_expire_minutes: 60,
};

export default function EmailConfigPage() {
  const token = useAuthStore((s) => s.token);
  const user = useAuthStore((s) => s.user);
  const queryClient = useQueryClient();
  const [form, setForm] = useState<MailSettings>(defaultSettings);
  const [testEmail, setTestEmail] = useState("");

  const { data, isLoading, isError } = useQuery({
    queryKey: ["admin", "mail-settings"],
    queryFn: () => adminMailService.getSettings(token!),
    enabled: Boolean(token) && user?.role === "admin",
  });

  useEffect(() => {
    if (data?.data) setForm({ ...defaultSettings, ...data.data });
  }, [data]);

  useEffect(() => {
    if (user?.email && !testEmail) setTestEmail(user.email);
  }, [user?.email, testEmail]);

  const payload = () => ({
    ...form,
    password: form.password || undefined,
  });

  const saveMutation = useMutation({
    mutationFn: () => adminMailService.updateSettings(token!, payload()),
    onSuccess: (res) => {
      queryClient.setQueryData(["admin", "mail-settings"], res);
      if (res.data) setForm({ ...defaultSettings, ...res.data });
      notifications.show({ title: "Salvo", message: "SMTP atualizado.", color: "green" });
    },
    onError: (e: Error) => notifications.show({ title: "Erro", message: e.message, color: "red" }),
  });

  const testConnMutation = useMutation({
    mutationFn: () => adminMailService.testConnection(token!, payload()),
    onSuccess: (res) => {
      notifications.show({ title: "SMTP", message: res.message ?? "OK", color: "green" });
      queryClient.invalidateQueries({ queryKey: ["admin", "mail-settings"] });
    },
    onError: (e: Error) => notifications.show({ title: "Falha", message: e.message, color: "red" }),
  });

  const sendTestMutation = useMutation({
    mutationFn: () => adminMailService.sendTest(token!, testEmail, payload()),
    onSuccess: (res) =>
      notifications.show({
        title: "E-mail enviado",
        message: res.message ?? "Verifique a caixa de entrada.",
        color: "green",
      }),
    onError: (e: Error) => notifications.show({ title: "Falha", message: e.message, color: "red" }),
  });

  const status = form.connection_status ?? "unknown";
  const connected = status === "connected";

  if (user?.role !== "admin") {
    return (
      <DashboardPage title="E-mail">
        <Alert color="red">Acesso restrito a administradores.</Alert>
      </DashboardPage>
    );
  }

  return (
    <DashboardPage title="E-mail / SMTP">
      <PageHeader
        title="E-mail / SMTP"
        description="Configure o envio transacional, teste a conexão e valide e-mails reais."
        action={
          <Button component={Link} href="/dashboard/logs/emails" variant="light" color="nogahost">
            Ver logs de e-mail
          </Button>
        }
      />

      {isLoading && <Loader color="nogahost" />}
      {isError && <Alert color="red">Não foi possível carregar as configurações.</Alert>}

      <Stack gap="lg" maw={720}>
        <GlassCard>
          <Group justify="space-between" mb="md">
            <Group gap="sm">
              <Mail size={22} color={colors.primary} />
              <Text fw={700} c={colors.white}>
                Status da conexão
              </Text>
            </Group>
            <Badge color={connected ? "green" : status === "error" ? "red" : "gray"} variant="light">
              {connected ? "🟢 Conectado" : status === "error" ? "🔴 Erro de conexão" : "Aguardando teste"}
            </Badge>
          </Group>
          {form.connection_message && (
            <Text size="sm" c="dimmed">
              {form.connection_message}
            </Text>
          )}
        </GlassCard>

        <GlassCard>
          <Stack gap="md">
            <Switch
              label="Ativar SMTP"
              checked={form.enabled}
              onChange={(e) => setForm((f) => ({ ...f, enabled: e.currentTarget.checked }))}
            />

            <TextInput
              label="Nome do remetente"
              value={form.from_name}
              onChange={(e) => setForm((f) => ({ ...f, from_name: e.target.value }))}
            />
            <TextInput
              label="E-mail remetente"
              type="email"
              value={form.from_address}
              onChange={(e) => setForm((f) => ({ ...f, from_address: e.target.value }))}
            />
            <TextInput
              label="Host SMTP"
              value={form.host}
              onChange={(e) => setForm((f) => ({ ...f, host: e.target.value }))}
            />
            <Group grow>
              <NumberInput
                label="Porta SMTP"
                value={form.port}
                onChange={(v) => setForm((f) => ({ ...f, port: Number(v) || 465 }))}
              />
              <Select
                label="Criptografia"
                value={form.encryption}
                data={[
                  { value: "ssl", label: "SSL" },
                  { value: "tls", label: "TLS" },
                  { value: "none", label: "Nenhuma" },
                ]}
                onChange={(v) =>
                  setForm((f) => ({ ...f, encryption: (v as MailSettings["encryption"]) ?? "ssl" }))
                }
              />
            </Group>
            <TextInput
              label="Usuário SMTP"
              value={form.username}
              onChange={(e) => setForm((f) => ({ ...f, username: e.target.value }))}
            />
            <PasswordInput
              label="Senha SMTP"
              placeholder={form.password_configured ? "•••••••• (mantém a atual)" : "Senha"}
              value={form.password}
              onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
            />
            <NumberInput
              label="Tempo limite (segundos)"
              value={form.timeout}
              onChange={(v) => setForm((f) => ({ ...f, timeout: Number(v) || 30 }))}
            />
            <TextInput
              label="Responder para"
              type="email"
              value={form.reply_to}
              onChange={(e) => setForm((f) => ({ ...f, reply_to: e.target.value }))}
            />
            <TextInput
              label="E-mail administrativo"
              description="Recebe alertas (ex.: novo cadastro)"
              type="email"
              value={form.admin_email}
              onChange={(e) => setForm((f) => ({ ...f, admin_email: e.target.value }))}
            />
            <NumberInput
              label="Expiração do link de senha (minutos)"
              value={form.password_reset_expire_minutes}
              onChange={(v) =>
                setForm((f) => ({ ...f, password_reset_expire_minutes: Number(v) || 60 }))
              }
            />

            <Group>
              <PrimaryButton
                leftSection={<Save size={16} />}
                loading={saveMutation.isPending}
                onClick={() => saveMutation.mutate()}
              >
                Salvar
              </PrimaryButton>
              <Button
                variant="light"
                color="nogahost"
                leftSection={<PlugZap size={16} />}
                loading={testConnMutation.isPending}
                onClick={() => testConnMutation.mutate()}
              >
                Testar conexão SMTP
              </Button>
            </Group>
          </Stack>
        </GlassCard>

        <GlassCard>
          <Stack gap="md">
            <Text fw={700} c={colors.white}>
              Enviar e-mail de teste
            </Text>
            <TextInput
              label="Destinatário"
              type="email"
              value={testEmail}
              onChange={(e) => setTestEmail(e.target.value)}
            />
            <Button
              color="nogahost"
              leftSection={<Send size={16} />}
              loading={sendTestMutation.isPending}
              onClick={() => sendTestMutation.mutate()}
            >
              Enviar e-mail teste
            </Button>
          </Stack>
        </GlassCard>
      </Stack>
    </DashboardPage>
  );
}
