"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowRight } from "lucide-react";
import { Box, Checkbox, Container, SimpleGrid, Stack, Text } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { Logo } from "@/components/brand/Logo";
import { ModernFormSection } from "@/components/ui/ModernFormSection";
import { ModernFormShell } from "@/components/ui/ModernFormShell";
import { ModernPasswordInput, ModernTextInput } from "@/components/ui/ModernFormFields";
import { PrimaryButton } from "@/components/ui/PrimaryButton";
import { registerUser } from "@/lib/registerUser";
import {
  buildLoginUrl,
  CONTRATAR_PATH,
  sanitizeRedirect,
} from "@/lib/authRedirect";
import { useAuthStore } from "@/store/authStore";
import { useBrandColors } from "@/hooks/useBrandColors";
import { isValidEmail } from "@/utils/brDocuments";
import { colors } from "@/styles/tokens";

function RegisterForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const setAuth = useAuthStore((s) => s.setAuth);
  const theme = useBrandColors();
  const redirectTo = sanitizeRedirect(searchParams.get("redirect"));
  const isConfigurator = redirectTo.startsWith(CONTRATAR_PATH);

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!name.trim() || name.trim().length < 3) {
      notifications.show({
        color: "red",
        title: "Nome",
        message: "Informe seu nome completo.",
      });
      return;
    }
    if (!isValidEmail(email)) {
      notifications.show({
        color: "red",
        title: "E-mail",
        message: "Informe um e-mail válido.",
      });
      return;
    }
    if (password.length < 8) {
      notifications.show({
        color: "red",
        title: "Senha",
        message: "A senha deve ter no mínimo 8 caracteres.",
      });
      return;
    }
    if (password !== confirmPassword) {
      notifications.show({
        color: "red",
        title: "Senha",
        message: "As senhas não coincidem.",
      });
      return;
    }
    if (!acceptedTerms) {
      notifications.show({
        color: "red",
        title: "Termos",
        message: "Aceite os Termos de Uso para continuar.",
      });
      return;
    }

    setLoading(true);
    try {
      const { user, token } = await registerUser({
        name: name.trim(),
        email: email.trim(),
        password,
        passwordConfirmation: confirmPassword,
      });
      setAuth(user, token);
      notifications.show({
        color: "green",
        title: "Conta criada",
        message: isConfigurator
          ? "Agora você pode configurar seu aplicativo."
          : `Bem-vindo, ${user.name}!`,
      });
      router.replace(redirectTo);
    } catch (err) {
      notifications.show({
        color: "red",
        title: "Não foi possível criar a conta",
        message:
          err instanceof Error ? err.message : "Tente novamente em instantes.",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container
      size={520}
      py={{ base: 40, sm: 56, md: 72 }}
      px="md"
      style={{ width: "100%", flex: 1 }}
    >
      <Stack gap="xl" maw={520} mx="auto">
        <Logo href="/" linkLabel="Voltar para a página inicial" />
        <Stack gap={6}>
          <Text
            fw={700}
            size="xl"
            className="noga-auth-page-title"
            style={{ color: theme.heading, letterSpacing: "-0.02em" }}
          >
            Criar conta
          </Text>
          <Text className="noga-auth-page-subtitle" style={{ color: theme.muted, lineHeight: 1.6 }}>
            {isConfigurator
              ? "Para acessar o configurador e montar seu aplicativo, crie sua conta NOGA CODE."
              : "Preencha seus dados para acessar o painel NOGA CODE."}
          </Text>
        </Stack>

        <form onSubmit={handleSubmit}>
          <ModernFormShell>
            <Stack gap="xl">
              <ModernFormSection step={1} title="Dados de acesso">
                <ModernTextInput
                  label="Nome completo"
                  placeholder="Seu nome completo"
                  required
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
                <ModernTextInput
                  label="E-mail"
                  type="email"
                  placeholder="voce@empresa.com"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
              </ModernFormSection>

              <ModernFormSection step={2} title="Senha de acesso">
                <SimpleGrid cols={{ base: 1, sm: 2 }}>
                  <ModernPasswordInput
                    label="Senha"
                    placeholder="Mínimo 8 caracteres"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <ModernPasswordInput
                    label="Confirmar senha"
                    placeholder="Repita a senha"
                    required
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                  />
                </SimpleGrid>
              </ModernFormSection>

              <Box
                p="md"
                style={{
                  borderRadius: 12,
                  background: "rgba(0, 0, 0, 0.25)",
                  border: "1px solid rgba(255, 255, 255, 0.08)",
                }}
              >
                <Checkbox
                  color="nogahost"
                  checked={acceptedTerms}
                  onChange={(e) => setAcceptedTerms(e.currentTarget.checked)}
                  label={
                    <Text size="sm" style={{ color: colors.grayMedium, lineHeight: 1.5 }}>
                      Declaro que li e concordo com os{" "}
                      <Link href="/termos-de-uso" style={{ color: colors.primary }}>
                        Termos de Uso
                      </Link>{" "}
                      e{" "}
                      <Link
                        href="/politica-de-privacidade"
                        style={{ color: colors.primary }}
                      >
                        Política de Privacidade
                      </Link>
                      .
                    </Text>
                  }
                />
              </Box>

              <PrimaryButton
                type="submit"
                fullWidth
                size="lg"
                loading={loading}
                rightSection={<ArrowRight size={18} />}
              >
                {isConfigurator ? "Criar conta e configurar app" : "Criar minha conta"}
              </PrimaryButton>
            </Stack>
          </ModernFormShell>
        </form>

        <Text size="sm" ta="center" style={{ color: theme.muted }}>
          Já tem conta?{" "}
          <Link
            href={buildLoginUrl(redirectTo)}
            style={{ color: colors.primary, fontWeight: 600 }}
          >
            Entrar
          </Link>
        </Text>
      </Stack>
    </Container>
  );
}

export default function RegisterPage() {
  return (
    <Suspense fallback={null}>
      <RegisterForm />
    </Suspense>
  );
}
