"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { ArrowLeft, Mail } 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 { ModernTextInput } from "@/components/ui/ModernFormFields";
import { PrimaryButton } from "@/components/ui/PrimaryButton";
import { buildLoginUrl } from "@/lib/authRedirect";
import { authService } from "@/services/authService";
import { useBrandColors } from "@/hooks/useBrandColors";
import { colors } from "@/styles/tokens";

function ForgotPasswordForm() {
  const searchParams = useSearchParams();
  const theme = useBrandColors();
  const redirect = searchParams.get("redirect");
  const loginHref = buildLoginUrl(redirect ?? undefined);

  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await authService.forgotPassword(email.trim());
      setSent(true);
      notifications.show({
        color: "green",
        title: "E-mail enviado",
        message: res.message ?? "Verifique sua caixa de entrada e o spam.",
      });
    } catch (err) {
      notifications.show({
        color: "red",
        title: "Não foi possível enviar",
        message: err instanceof Error ? err.message : "Tente novamente em instantes.",
      });
    } 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" }}
            >
              Esqueci minha senha
            </Text>
            <Text className="noga-auth-page-subtitle" style={{ color: theme.muted, lineHeight: 1.6 }}>
              {sent
                ? "Se o e-mail estiver cadastrado, enviamos um link para você criar uma nova senha."
                : "Informe o e-mail da sua conta. Enviaremos um link seguro para redefinir a senha."}
            </Text>
          </Stack>

          {!sent ? (
            <form onSubmit={handleSubmit}>
              <ModernFormShell>
                <Stack gap="lg">
                  <ModernFormSection step={1} title="Recuperar acesso">
                    <ModernTextInput
                      label="E-mail"
                      placeholder="voce@empresa.com"
                      type="email"
                      required
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />
                  </ModernFormSection>

                  <PrimaryButton
                    type="submit"
                    fullWidth
                    size="lg"
                    loading={loading}
                    leftSection={<Mail size={18} />}
                  >
                    Enviar link de redefinição
                  </PrimaryButton>
                </Stack>
              </ModernFormShell>
            </form>
          ) : (
            <PrimaryButton
              component={Link}
              href={loginHref}
              fullWidth
              size="lg"
              variant="light"
            >
              Voltar para o login
            </PrimaryButton>
          )}

          <Text size="sm" ta="center" style={{ color: theme.muted }}>
            <Link
              href={loginHref}
              style={{
                color: colors.primary,
                fontWeight: 600,
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              <ArrowLeft size={16} />
              Voltar para entrar
            </Link>
          </Text>
        </Stack>
      </Container>
      <AuthFooter />
    </>
  );
}

export default function ForgotPasswordPage() {
  return (
    <Suspense fallback={null}>
      <ForgotPasswordForm />
    </Suspense>
  );
}
