"use client";

import {
  Alert,
  Badge,
  Button,
  CopyButton,
  Group,
  Loader,
  PasswordInput,
  SimpleGrid,
  Stack,
  Switch,
  Text,
  TextInput,
  Tooltip,
} from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, Copy, ExternalLink, PlugZap, Save } 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 { MERCADO_PAGO_SUBSCRIPTIONS_DOC, paymentMethods } from "@/data/commerce";
import {
  adminPaymentSettingsService,
  type MercadoPagoSettings,
  type PaymentMethodSetting,
} from "@/services/adminPaymentSettingsService";
import { useAuthStore } from "@/store/authStore";
import { colors } from "@/styles/tokens";

const defaultMp: MercadoPagoSettings = {
  public_key: "",
  access_token: "",
  client_id: "",
  client_secret: "",
  webhook_secret: "",
  back_url: "http://localhost:3000/dashboard/assinaturas?welcome=1",
};

export default function PagamentosConfigPage() {
  const token = useAuthStore((s) => s.token);
  const user = useAuthStore((s) => s.user);
  const queryClient = useQueryClient();

  const [mp, setMp] = useState<MercadoPagoSettings>(defaultMp);
  const [methods, setMethods] = useState<PaymentMethodSetting[]>(() =>
    paymentMethods.map((m) => ({
      id: m.id,
      gateway: m.gateway,
      label: m.label,
      description: m.description,
      icon: m.icon,
      enabled: true,
      featured: Boolean(m.featured),
      supports_subscription: Boolean(m.supportsSubscription),
    })),
  );
  const [webhookUrl, setWebhookUrl] = useState("http://localhost:8000/api/v1/webhooks/mercadopago");

  const { data, isLoading, isError } = useQuery({
    queryKey: ["admin", "payment-settings"],
    queryFn: () => adminPaymentSettingsService.get(token!),
    enabled: Boolean(token) && user?.role === "admin",
  });

  useEffect(() => {
    if (!data?.data) return;
    const payload = data.data;
    setMp({ ...defaultMp, ...payload.mercadopago });
    setMethods(payload.methods ?? []);
    setWebhookUrl(payload.webhook_url ?? "");
  }, [data]);

  const saveMutation = useMutation({
    mutationFn: () =>
      adminPaymentSettingsService.update(token!, {
        mercadopago: mp,
        methods,
      }),
    onSuccess: (res) => {
      queryClient.setQueryData(["admin", "payment-settings"], res);
      notifications.show({
        title: "Salvo",
        message: res.message ?? "Configurações de pagamento atualizadas.",
        color: "green",
      });
      if (res.data) {
        setMp({ ...defaultMp, ...res.data.mercadopago });
        setMethods(res.data.methods ?? []);
        setWebhookUrl(res.data.webhook_url ?? "");
      }
    },
    onError: (err: Error) => {
      notifications.show({ title: "Erro", message: err.message, color: "red" });
    },
  });

  const testMutation = useMutation({
    mutationFn: () => adminPaymentSettingsService.testMercadoPago(token!),
    onSuccess: (res) => {
      const info = res.data;
      notifications.show({
        title: "Mercado Pago conectado",
        message: info?.nickname
          ? `Conta: ${info.nickname}${info.email ? ` (${info.email})` : ""}`
          : res.message ?? "Conexão OK.",
        color: "green",
      });
    },
    onError: (err: Error) => {
      notifications.show({ title: "Falha no teste", message: err.message, color: "red" });
    },
  });

  const toggleMethod = (id: string, enabled: boolean) => {
    setMethods((prev) => prev.map((m) => (m.id === id ? { ...m, enabled } : m)));
  };

  if (user?.role !== "admin") {
    return (
      <DashboardPage title="Pagamentos">
        <Alert color="red">Acesso restrito a administradores.</Alert>
      </DashboardPage>
    );
  }

  return (
    <DashboardPage title="Pagamentos">
      <PageHeader
        title="Pagamentos e gateways"
        description="Mercado Pago, métodos aceitos no checkout e URL de webhook."
        actions={
          <Button component={Link} href="/dashboard/configuracoes" variant="subtle" size="sm">
            Voltar às configurações
          </Button>
        }
      />

      {isLoading && (
        <Group justify="center" py="xl">
          <Loader color="nogahost" />
        </Group>
      )}

      {isError && (
        <Alert color="yellow" title="API em localhost:8000 indisponível">
          O frontend está no ar; o backend Laravel precisa estar em{" "}
          <Text span ff="monospace" size="sm">
            http://localhost:8000
          </Text>
          . As chaves do Mercado Pago no arquivo{" "}
          <Text span ff="monospace" size="sm">
            backend/.env
          </Text>{" "}
          continuam valendo para o checkout quando a API voltar.
        </Alert>
      )}

      {(!isLoading && !isError) || isError ? (
        <Stack gap="xl">
          <GlassCard>
            <Stack gap="md">
              <Group justify="space-between" align="flex-start">
                <Stack gap={4}>
                  <Text fw={700} c={colors.white}>
                    Mercado Pago
                  </Text>
                  <Text size="sm" c="dimmed">
                    Assinaturas recorrentes (Subscriptions API). Chaves salvas criptografadas no
                    banco; o .env continua como fallback.
                  </Text>
                </Stack>
                <Button
                  component="a"
                  href={MERCADO_PAGO_SUBSCRIPTIONS_DOC}
                  target="_blank"
                  rel="noreferrer"
                  variant="light"
                  size="xs"
                  rightSection={<ExternalLink size={14} />}
                >
                  Documentação
                </Button>
              </Group>

              <SimpleGrid cols={{ base: 1, md: 2 }} spacing="md">
                <TextInput
                  label="Public Key"
                  placeholder="APP_USR-..."
                  value={mp.public_key}
                  onChange={(e) => setMp((p) => ({ ...p, public_key: e.target.value }))}
                />
                <PasswordInput
                  label="Access Token"
                  placeholder={
                    mp.access_token_configured
                      ? "••••••••  (já configurado — deixe vazio para manter)"
                      : "APP_USR-..."
                  }
                  value={mp.access_token}
                  onChange={(e) => setMp((p) => ({ ...p, access_token: e.target.value }))}
                />
                <TextInput
                  label="Client ID"
                  value={mp.client_id}
                  onChange={(e) => setMp((p) => ({ ...p, client_id: e.target.value }))}
                />
                <PasswordInput
                  label="Client Secret"
                  placeholder={
                    mp.client_secret_configured
                      ? "••••••••  (já configurado — deixe vazio para manter)"
                      : "Seu client secret"
                  }
                  value={mp.client_secret}
                  onChange={(e) => setMp((p) => ({ ...p, client_secret: e.target.value }))}
                />
                <PasswordInput
                  label="Webhook Secret (opcional)"
                  placeholder={
                    mp.webhook_secret_configured
                      ? "••••••••  (já configurado)"
                      : "Assinatura do webhook"
                  }
                  value={mp.webhook_secret}
                  onChange={(e) => setMp((p) => ({ ...p, webhook_secret: e.target.value }))}
                />
                <TextInput
                  label="URL de retorno (back_url)"
                  description="Após aprovar assinatura no MP, o cliente volta para esta URL."
                  value={mp.back_url}
                  onChange={(e) => setMp((p) => ({ ...p, back_url: e.target.value }))}
                />
              </SimpleGrid>

              <Stack gap="xs">
                <Text size="sm" fw={600} c={colors.grayLight}>
                  Webhook (notificações de pagamento)
                </Text>
                <Group gap="sm">
                  <TextInput
                    flex={1}
                    readOnly
                    value={webhookUrl}
                    styles={{ input: { fontFamily: "monospace", fontSize: 12 } }}
                  />
                  <CopyButton value={webhookUrl}>
                    {({ copied, copy }) => (
                      <Tooltip label={copied ? "Copiado" : "Copiar URL"}>
                        <Button variant="light" onClick={copy} px="sm">
                          {copied ? <Check size={16} /> : <Copy size={16} />}
                        </Button>
                      </Tooltip>
                    )}
                  </CopyButton>
                </Group>
                <Text size="xs" c="dimmed">
                  Cadastre esta URL no painel do Mercado Pago em Webhooks → eventos de pagamento e
                  assinatura.
                </Text>
              </Stack>

              <Group>
                <Button
                  variant="light"
                  leftSection={<PlugZap size={16} />}
                  loading={testMutation.isPending}
                  onClick={() => testMutation.mutate()}
                >
                  Testar conexão
                </Button>
                {(mp.access_token_configured || mp.public_key) && (
                  <Badge color="green" variant="light">
                    Credenciais no painel
                  </Badge>
                )}
              </Group>
            </Stack>
          </GlassCard>

          <GlassCard>
            <Stack gap="lg">
              <Stack gap={4}>
                <Text fw={700} c={colors.white}>
                  Métodos no checkout
                </Text>
                <Text size="sm" c="dimmed">
                  Ative ou desative cada forma de pagamento exibida em /contratar.
                </Text>
              </Stack>

              {methods.map((method) => (
                <Group
                  key={method.id}
                  justify="space-between"
                  wrap="nowrap"
                  p="md"
                  style={{
                    borderRadius: 12,
                    border: "1px solid rgba(0,155,255,0.12)",
                    background: colors.bgSecondary,
                  }}
                >
                  <Stack gap={2}>
                    <Group gap="xs">
                      <Text fw={600} size="sm" c={colors.white}>
                        {method.label}
                      </Text>
                      {method.featured && (
                        <Badge size="xs" color="nogahost">
                          Destaque
                        </Badge>
                      )}
                      {method.supports_subscription && (
                        <Badge size="xs" variant="outline" color="nogahost">
                          Recorrente
                        </Badge>
                      )}
                    </Group>
                    <Text size="xs" c="dimmed">
                      {method.description}
                    </Text>
                    <Text size="xs" c="dimmed" ff="monospace">
                      gateway: {method.gateway}
                    </Text>
                  </Stack>
                  <Switch
                    checked={method.enabled}
                    onChange={(e) => toggleMethod(method.id, e.currentTarget.checked)}
                    color="nogahost"
                    label={method.enabled ? "Ativo" : "Inativo"}
                  />
                </Group>
              ))}
            </Stack>
          </GlassCard>

          <Group justify="flex-end">
            <PrimaryButton
              leftSection={<Save size={18} />}
              loading={saveMutation.isPending}
              onClick={() => saveMutation.mutate()}
            >
              Salvar configurações
            </PrimaryButton>
          </Group>
        </Stack>
      ) : null}
    </DashboardPage>
  );
}
