"use client";

import { Suspense, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowRight } 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, ModernTextInput } from "@/components/ui/ModernFormFields";
import { PrimaryButton } from "@/components/ui/PrimaryButton";
import { loginUser } from "@/lib/loginUser";
import {
  buildRegisterUrl,
  CONTRATAR_PATH,
  sanitizeRedirect,
} from "@/lib/authRedirect";
import { useAuthStore } from "@/store/authStore";
import { useBrandColors } from "@/hooks/useBrandColors";
import { colors } from "@/styles/tokens";

function LoginForm() {
  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 [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const { user, token } = await loginUser({ email, password });
      setAuth(user, token);
      notifications.show({
        color: "green",
        title: "Bem-vindo",
        message: `Olá, ${user.name}`,
      });
      if (isConfigurator) {
        router.replace(redirectTo);
        return;
      }
      const target =
        user.role === "admin" ? "/dashboard" : "/dashboard/assinaturas";
      router.replace(target);
    } catch (err) {
      notifications.show({
        color: "red",
        title: "Não foi possível entrar",
        message: err instanceof Error ? err.message : "Verifique e-mail e 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" }}
            >
              Entrar
            </Text>
            <Text className="noga-auth-page-subtitle" style={{ color: theme.muted, lineHeight: 1.6 }}>
              {isConfigurator
                ? "Entre com sua conta para continuar a configuração do seu aplicativo."
                : "Entre com seu e-mail e senha para acessar o painel NOGA CODE."}
            </Text>
          </Stack>

          <form onSubmit={handleSubmit}>
            <ModernFormShell>
              <Stack gap="lg">
                <ModernFormSection step={1} title="Acesso à conta">
                  <ModernTextInput
                    label="E-mail"
                    placeholder="voce@empresa.com"
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                  <ModernPasswordInput
                    label="Senha"
                    placeholder="Sua senha"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                  />
                  <Text size="sm" ta="right">
                    <Link
                      href={`/esqueci-senha?redirect=${encodeURIComponent(redirectTo)}`}
                      style={{ color: colors.primary, fontWeight: 600 }}
                    >
                      Esqueci minha senha
                    </Link>
                  </Text>
                </ModernFormSection>

                <PrimaryButton
                  type="submit"
                  fullWidth
                  size="lg"
                  loading={loading}
                  rightSection={<ArrowRight size={18} />}
                >
                  Entrar
                </PrimaryButton>
              </Stack>
            </ModernFormShell>
          </form>

          <Text size="sm" ta="center" style={{ color: theme.muted }}>
            Não tem conta?{" "}
            <Link
              href={buildRegisterUrl(redirectTo)}
              style={{ color: colors.primary, fontWeight: 600 }}
            >
              Criar conta
            </Link>
          </Text>
        </Stack>
      </Container>
      <AuthFooter />
    </>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginForm />
    </Suspense>
  );
}
