"use client";

import { FormEvent, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useAppLocale } from "@/features/i18n/LocaleProvider";
import { getAuthMessages } from "@/features/i18n/messages/auth";

type PasswordStrengthLabel = "weak" | "medium" | "strong";

function getPasswordStrengthLabel(password: string): PasswordStrengthLabel | null {
  if (!password || password.length < 4) {
    return null;
  }

  let score = 0;
  if (/[a-z]/.test(password)) score += 1;
  if (/[A-Z]/.test(password)) score += 1;
  if (/[0-9]/.test(password)) score += 1;
  if (/[^a-zA-Z0-9]/.test(password)) score += 1;
  if (password.length >= 12) score += 1;

  if (password.length < 8 || score <= 2) {
    return "weak";
  }

  if (score === 3) {
    return "medium";
  }

  return "strong";
}

export default function SignupPage() {
  const router = useRouter();

  const locale = useAppLocale();
  const { signup: t } = getAuthMessages(locale);

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [passwordConfirm, setPasswordConfirm] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;

    const checkAuth = async () => {
      try {
        const res = await fetch("/api/auth/me");
        if (!cancelled && res.ok) {
          router.push("/dashboard");
        }
      } catch {
        // ignore
      }
    };

    void checkAuth();

    return () => {
      cancelled = true;
    };
  }, [router]);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    setError(null);
    if (password !== passwordConfirm) {
      setError(t.mismatchError);
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });

      if (!res.ok) {
        try {
          const data = await res.json();
          setError(data?.message ?? t.signupFailedFallbackError);
        } catch {
          setError(t.signupFailedFallbackError);
        }
        setLoading(false);
        return;
      }

      router.push("/dashboard");
    } catch {
      setError(t.errorNetwork);
    } finally {
      setLoading(false);
    }
  };

  const strengthLabel = getPasswordStrengthLabel(password);
  let strengthText: string | null = null;
  if (strengthLabel) {
    strengthText =
      strengthLabel === "weak"
        ? t.passwordStrengthWeak
        : strengthLabel === "medium"
          ? t.passwordStrengthMedium
          : t.passwordStrengthStrong;
  }

  return (
    <main className="min-h-screen flex items-center justify-center bg-slate-100 text-slate-900 dark:bg-slate-950 dark:text-slate-50">
      <div className="w-full max-w-sm rounded-lg border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-800 dark:bg-slate-900/70">
        <h1 className="text-lg font-semibold mb-1">{t.title}</h1>
        <p className="text-xs text-slate-500 mb-4 dark:text-slate-400">{t.description}</p>

        {error && <p className="mb-3 text-xs text-red-300">{error}</p>}

        <form onSubmit={handleSubmit} className="space-y-3 text-xs">
          <div className="space-y-1">
            <label htmlFor="email" className="block text-slate-800 dark:text-slate-200">
              {t.emailLabel}
            </label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full rounded border border-slate-300 bg-white px-2 py-1 text-xs text-slate-900 focus:outline-none focus:ring-1 focus:ring-sky-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50"
              required
            />
          </div>

          <div className="space-y-1">
            <label htmlFor="password" className="block text-slate-800 dark:text-slate-200">
              {t.passwordLabel}
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full rounded border border-slate-300 bg-white px-2 py-1 text-xs text-slate-900 focus:outline-none focus:ring-1 focus:ring-sky-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50"
              required
              minLength={8}
            />
          </div>

          {strengthLabel && (
            <div className="mt-1 space-y-1">
              <div className="h-1.5 rounded-full bg-slate-200/70 dark:bg-slate-700/70 overflow-hidden">
                <div
                  data-testid="password-strength-bar"
                  className={
                    "h-full transition-all " +
                    (strengthLabel === "weak"
                      ? "w-1/3 bg-red-500"
                      : strengthLabel === "medium"
                        ? "w-2/3 bg-amber-500"
                        : "w-full bg-emerald-600")
                  }
                />
              </div>
              <p
                className={
                  "text-[11px] " +
                  (strengthLabel === "weak"
                    ? "text-red-500 dark:text-red-300"
                    : strengthLabel === "medium"
                      ? "text-amber-500 dark:text-amber-300"
                      : "text-emerald-600 dark:text-emerald-300")
                }
              >
                {t.passwordStrengthPrefix} {strengthText}
              </p>
            </div>
          )}

          <div className="space-y-1">
            <label htmlFor="passwordConfirm" className="block text-slate-800 dark:text-slate-200">
              {t.passwordConfirmLabel}
            </label>
            <input
              id="passwordConfirm"
              type="password"
              value={passwordConfirm}
              onChange={(e) => setPasswordConfirm(e.target.value)}
              className="w-full rounded border border-slate-300 bg-white px-2 py-1 text-xs text-slate-900 focus:outline-none focus:ring-1 focus:ring-sky-500 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-50"
              required
              minLength={8}
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className="mt-2 w-full inline-flex items-center justify-center gap-1 rounded bg-sky-600 hover:bg-sky-500 disabled:opacity-40 disabled:cursor-not-allowed px-3 py-1 text-xs font-medium"
          >
            {loading ? t.submitLoading : t.submitIdle}
          </button>
        </form>

        <p className="mt-4 text-[11px] text-slate-500 dark:text-slate-400">
          {t.loginPromptPrefix}
          {" "}
          <Link href="/login" className="text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline">
            {t.loginLinkText}
          </Link>
          {t.loginPromptSuffix && " "}
          {t.loginPromptSuffix}
        </p>
      </div>
    </main>
  );
}
