"use client";

import { useState, useEffect, useCallback, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "../auth-context";
import { invitesApi } from "../api";
import { authFormStyles as styles } from "../styles/auth-form";
import { LanguageSelector } from "../components/LanguageSelector";
import { useTranslation } from "../hooks/useTranslation";

function SignupContent() {
  const searchParams = useSearchParams();
  const initialCode = searchParams.get("code") || "";

  const [inviteCode, setInviteCode] = useState(initialCode);
  const [inviteValid, setInviteValid] = useState<boolean | null>(null);
  const [inviteError, setInviteError] = useState("");
  const [isCheckingInvite, setIsCheckingInvite] = useState(false);
  const [isCheckingInitialCode, setIsCheckingInitialCode] = useState(!!initialCode);

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const { user, register } = useAuth();
  const router = useRouter();
  const t = useTranslation("auth");

  // Redirect if already logged in
  useEffect(() => {
    if (user) {
      router.push("/");
    }
  }, [user, router]);

  const checkInvite = useCallback(async (code: string) => {
    if (!code.trim()) {
      setInviteValid(null);
      setInviteError("");
      return;
    }

    setIsCheckingInvite(true);
    setInviteError("");

    try {
      const response = await invitesApi.checkInvite(code.trim());

      if (response.valid) {
        setInviteValid(true);
        setInviteError("");
      } else {
        setInviteValid(false);
        setInviteError(response.error || t("signup.invalidInviteCode"));
      }
    } catch {
      setInviteValid(false);
      setInviteError(t("signup.failedToVerify"));
    } finally {
      setIsCheckingInvite(false);
    }
  }, []);

  // Check invite code on mount if provided in URL
  useEffect(() => {
    if (initialCode) {
      checkInvite(initialCode).finally(() => setIsCheckingInitialCode(false));
    }
  }, [initialCode, checkInvite]);

  const handleInviteSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    checkInvite(inviteCode);
  };

  const handleSignupSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (password !== confirmPassword) {
      setError(t("signup.passwordsDoNotMatch"));
      return;
    }

    if (password.length < 6) {
      setError(t("signup.passwordTooShort"));
      return;
    }

    setIsSubmitting(true);

    try {
      await register(email, password, inviteCode.trim());
      router.push("/");
    } catch (err) {
      setError(err instanceof Error ? err.message : t("signup.registrationFailed"));
    } finally {
      setIsSubmitting(false);
    }
  };

  // Show loading or redirect if user is already logged in
  if (user) {
    return null;
  }

  // Show loading state while checking initial code from URL
  if (isCheckingInitialCode) {
    return (
      <main style={styles.main}>
        <div style={{ position: "absolute", top: "1rem", right: "1rem" }}>
          <LanguageSelector />
        </div>
        <div style={styles.container}>
          <div style={styles.card}>
            <div style={{ textAlign: "center", color: "rgba(255,255,255,0.6)" }}>
              {t("signup.checkingInviteCode")}
            </div>
          </div>
        </div>
      </main>
    );
  }

  // Step 1: Enter invite code
  if (!inviteValid) {
    return (
      <main style={styles.main}>
        <div style={{ position: "absolute", top: "1rem", right: "1rem" }}>
          <LanguageSelector />
        </div>
        <div style={styles.container}>
          <div style={styles.card}>
            <div style={styles.header}>
              <h1 style={styles.title}>{t("signup.title")}</h1>
              <p style={styles.subtitle}>{t("signup.subtitle")}</p>
            </div>

            <form onSubmit={handleInviteSubmit} style={styles.form}>
              {inviteError && <div style={styles.error}>{inviteError}</div>}

              <div style={styles.field}>
                <label htmlFor="inviteCode" style={styles.label}>
                  {t("signup.inviteCode")}
                </label>
                <input
                  id="inviteCode"
                  type="text"
                  value={inviteCode}
                  onChange={(e) => {
                    setInviteCode(e.target.value);
                    setInviteError("");
                    setInviteValid(null);
                  }}
                  style={styles.input}
                  placeholder={t("signup.inviteCodePlaceholder")}
                  required
                  autoFocus
                />
                <span
                  style={{
                    ...styles.link,
                    fontSize: "0.8rem",
                    marginTop: "0.5rem",
                    display: "block",
                  }}
                >
                  {t("signup.inviteHint")}
                </span>
              </div>

              <button
                type="submit"
                style={{
                  ...styles.button,
                  opacity: isCheckingInvite ? 0.7 : 1,
                }}
                disabled={isCheckingInvite || !inviteCode.trim()}
              >
                {isCheckingInvite ? t("signup.checking") : t("signup.continue")}
              </button>
            </form>

            <p style={styles.footer}>
              {t("signup.alreadyHaveAccount")}{" "}
              <a href="/login" style={styles.link}>
                {t("signup.signIn")}
              </a>
            </p>
          </div>
        </div>
      </main>
    );
  }

  // Step 2: Enter email and password
  return (
    <main style={styles.main}>
      <div style={{ position: "absolute", top: "1rem", right: "1rem" }}>
        <LanguageSelector />
      </div>
      <div style={styles.container}>
        <div style={styles.card}>
          <div style={styles.header}>
            <h1 style={styles.title}>{t("signup.createAccountTitle")}</h1>
            <p style={styles.subtitle}>
              {t("signup.createAccountSubtitle")}{" "}
              <code
                style={{
                  background: "rgba(255,255,255,0.1)",
                  padding: "0.2rem 0.5rem",
                  borderRadius: "4px",
                  fontSize: "0.85rem",
                }}
              >
                {inviteCode}
              </code>
            </p>
          </div>

          <form onSubmit={handleSignupSubmit} style={styles.form}>
            {error && <div style={styles.error}>{error}</div>}

            <div style={styles.field}>
              <label htmlFor="email" style={styles.label}>
                {t("signup.email")}
              </label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                style={styles.input}
                placeholder={t("signup.emailPlaceholder")}
                required
                autoFocus
              />
            </div>

            <div style={styles.field}>
              <label htmlFor="password" style={styles.label}>
                {t("signup.password")}
              </label>
              <input
                id="password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                style={styles.input}
                placeholder={t("signup.passwordPlaceholder")}
                required
              />
            </div>

            <div style={styles.field}>
              <label htmlFor="confirmPassword" style={styles.label}>
                {t("signup.confirmPassword")}
              </label>
              <input
                id="confirmPassword"
                type="password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                style={styles.input}
                placeholder={t("signup.confirmPasswordPlaceholder")}
                required
              />
            </div>

            <button
              type="submit"
              style={{
                ...styles.button,
                opacity: isSubmitting ? 0.7 : 1,
              }}
              disabled={isSubmitting}
            >
              {isSubmitting ? t("signup.creatingAccount") : t("signup.createAccount")}
            </button>
          </form>

          <p style={styles.footer}>
            <button
              onClick={() => {
                setInviteValid(null);
                setInviteError("");
              }}
              style={{
                ...styles.link,
                background: "none",
                border: "none",
                cursor: "pointer",
                padding: 0,
              }}
            >
              {t("signup.useDifferentCode")}
            </button>
          </p>
        </div>
      </div>
    </main>
  );
}

export default function SignupPage() {
  return (
    <Suspense
      fallback={
        <main style={styles.main}>
          <div style={styles.container}>
            <div style={styles.card}>
              <div style={{ textAlign: "center", color: "rgba(255,255,255,0.6)" }}>Loading...</div>
            </div>
          </div>
        </main>
      }
    >
      <SignupContent />
    </Suspense>
  );
}
