"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowRight, KeyRound } from "lucide-react";
import { Container, Stack, Text } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { AuthFooter } from "@/components/auth/AuthFooter";
import { Logo } from "@/components/brand/Logo";
import { ModernFormSection } from "@/components/ui/ModernFormSection";
import { ModernFormShell } from "@/components/ui/ModernFormShell";
import { ModernPasswordInput } from "@/components/ui/ModernFormFields";
import { PrimaryButton } from "@/components/ui/PrimaryButton";
import { authService } from "@/services/authService";
import { useBrandColors } from "@/hooks/useBrandColors";
import { colors } from "@/styles/tokens";

function ResetPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const theme = useBrandColors();

  const token = searchParams.get("token") ?? "";
  const email = searchParams.get("email") ?? "";

  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");
  const [loading, setLoading] = useState(false);

  const invalidLink = !token || !email;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (password.length < 8) {
      notifications.show({
        color: "red",
        title: "Senha fraca",
        message: "Use no mínimo 8 caracteres.",
      });
      return;
    }

    if (password !== passwordConfirmation) {
      notifications.show({
        color: "red",
        title: "Senhas diferentes",
        message: "Confirme a mesma senha nos dois campos.",
      });
      return;
    }

    setLoading(true);
    try {
      await authService.resetPassword({
        email,
        token,
        password,
        password_confirmation: passwordConfirmation,
      });
      notifications.show({
        color: "green",
        title: "Senha atualizada",
        message: "Faça login com sua nova senha.",
      });
      router.replace("/login");
    } catch (err) {
      notifications.show({
        color: "red",
        title: "Não foi possível redefinir",
        message:
          err instanceof Error
            ? err.message
            : "O link pode ter expirado. Solicite um novo em Esqueci minha senha.",
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      <Container
        size={480}
        py={{ base: 40, sm: 56, md: 72 }}
        px="md"
        style={{ width: "100%", flex: 1 }}
      >
        <Stack gap="xl" maw={480} mx="auto">
          <Link href="/" style={{ textDecoration: "none", display: "inline-block" }}>
            <Logo static />
          </Link>
          <Stack gap={6}>
            <Text
              fw={700}
              size="xl"
              className="noga-auth-page-title"
              style={{ color: theme.heading, letterSpacing: "-0.02em" }}
            >
              Nova senha
            </Text>
            <Text className="noga-auth-page-subtitle" style={{ color: theme.muted, lineHeight: 1.6 }}>
              {invalidLink
                ? "Link inválido ou incompleto. Solicite um novo e-mail em Esqueci minha senha."
                : "Defina uma senha forte para sua conta NOGA CODE."}
            </Text>
          </Stack>

          {invalidLink ? (
            <PrimaryButton component={Link} href="/esqueci-senha" fullWidth size="lg">
              Solicitar novo link
            </PrimaryButton>
          ) : (
            <form onSubmit={handleSubmit}>
              <ModernFormShell>
                <Stack gap="lg">
                  <ModernFormSection step={1} title="Criar nova senha">
                    <Text size="sm" style={{ color: theme.muted }}>
                      Conta: <strong style={{ color: theme.heading }}>{email}</strong>
                    </Text>
                    <ModernPasswordInput
                      label="Nova 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={passwordConfirmation}
                      onChange={(e) => setPasswordConfirmation(e.target.value)}
                    />
                  </ModernFormSection>

                  <PrimaryButton
                    type="submit"
                    fullWidth
                    size="lg"
                    loading={loading}
                    leftSection={<KeyRound size={18} />}
                    rightSection={<ArrowRight size={18} />}
                  >
                    Salvar nova senha
                  </PrimaryButton>
                </Stack>
              </ModernFormShell>
            </form>
          )}

          <Text size="sm" ta="center" style={{ color: theme.muted }}>
            <Link href="/login" style={{ color: colors.primary, fontWeight: 600 }}>
              Ir para o login
            </Link>
          </Text>
        </Stack>
      </Container>
      <AuthFooter />
    </>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense fallback={null}>
      <ResetPasswordForm />
    </Suspense>
  );
}
