"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Eye, EyeOff, MailCheck } from "lucide-react";
import { createClient } from "@/lib/supabase/client";
import { SITE_NAME } from "@/lib/constants";
import DiscordButton from "@/components/DiscordButton";
import GoogleButton from "@/components/GoogleButton";
import { loginWithIdentifier, requestPasswordReset, resendConfirmationEmail } from "./actions";

declare global {
  interface Window {
    turnstile?: {
      render: (container: HTMLElement, options: {
        sitekey: string;
        action: string;
        callback: (token: string) => void;
        "expired-callback": () => void;
        "error-callback": () => void;
      }) => string;
      reset: (widgetId?: string) => void;
      remove: (widgetId: string) => void;
    };
  }
}

export default function LoginPage() {
  const router = useRouter();
  const supabase = useMemo(() => createClient(), []);
  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [loading, setLoading] = useState(false);
  const [turnstileToken, setTurnstileToken] = useState("");
  const [turnstileError, setTurnstileError] = useState("");
  const turnstileContainer = useRef<HTMLDivElement>(null);
  const turnstileWidgetId = useRef<string | null>(null);
  const turnstileSiteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "";

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    setError(params.get("error") || "");
    const initialParam = params.get("email") || params.get("username");
    if (initialParam) setIdentifier(initialParam);
    if (params.get("verified") === "true") {
      setNotice("Email verified successfully. Log in below to access your dashboard.");
    }

    supabase.auth.getSession().then(({ data }) => {
      if (data.session) {
        const nextParam = params.get("next");
        const target = nextParam && nextParam.startsWith("/") && !nextParam.startsWith("//") ? nextParam : "/dashboard";
        router.replace(target);
      }
    });
  }, [router, supabase]);

  useEffect(() => {
    if (!turnstileSiteKey || !turnstileContainer.current) return;
    let cancelled = false;
    let script = document.getElementById("cloudflare-turnstile-script") as HTMLScriptElement | null;
    let checkInterval: NodeJS.Timeout | null = null;

    const renderWidget = () => {
      if (cancelled || !window.turnstile || !turnstileContainer.current || turnstileWidgetId.current) return;
      turnstileWidgetId.current = window.turnstile.render(turnstileContainer.current, {
        sitekey: turnstileSiteKey,
        action: "login",
        callback: (token) => {
          setTurnstileToken(token);
          setTurnstileError("");
        },
        "expired-callback": () => {
          setTurnstileToken("");
          setTurnstileError("Verification expired. Please complete it again.");
        },
        "error-callback": () => {
          setTurnstileToken("");
          setTurnstileError("Could not load verification. Refresh the page and try again.");
        },
      });
    };

    if (window.turnstile) {
      renderWidget();
    } else {
      if (!script) {
        script = document.createElement("script");
        script.id = "cloudflare-turnstile-script";
        script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
        script.async = true;
        script.defer = true;
        document.head.appendChild(script);
      }
      script.addEventListener("load", renderWidget);
      script.addEventListener("error", () => {
        if (!cancelled) setTurnstileError("Could not load verification. Check your connection and try again.");
      }, { once: true });

      checkInterval = setInterval(() => {
        if (cancelled) return;
        if (window.turnstile && !turnstileWidgetId.current && turnstileContainer.current) {
          renderWidget();
          if (checkInterval) clearInterval(checkInterval);
        }
      }, 200);
    }

    return () => {
      cancelled = true;
      if (checkInterval) clearInterval(checkInterval);
      if (turnstileWidgetId.current && window.turnstile) {
        window.turnstile.remove(turnstileWidgetId.current);
        turnstileWidgetId.current = null;
      }
    };
  }, [turnstileSiteKey]);

  const [emailNotConfirmed, setEmailNotConfirmed] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [resendDone, setResendDone] = useState(false);
  const [forgotMode, setForgotMode] = useState(false);
  const [resetSent, setResetSent] = useState(false);
  const [resetLoading, setResetLoading] = useState(false);

  const submitReset = async () => {
    setError("");
    if (!identifier.trim()) return setError("Enter your username or email address.");
    setResetLoading(true);
    try {
      const origin = window.location.origin;
      const res = await requestPasswordReset({
        identifier: identifier.trim(),
        redirectTo: `${origin}/reset-password`,
      });

      if (res.error) {
        setError(res.error);
      } else {
        setResetSent(true);
      }
    } catch {
      setError("Could not send reset email. Check your connection and try again.");
    } finally {
      setResetLoading(false);
    }
  };

  const submit = async () => {
    setError("");
    setEmailNotConfirmed(false);
    setResendDone(false);
    if (!identifier.trim()) return setError("Enter your username or email address.");
    if (!password) return setError("Enter your password.");
    if (turnstileSiteKey && !turnstileToken) {
      return setError("Complete the verification challenge before continuing.");
    }

    setLoading(true);
    try {
      const res = await loginWithIdentifier({
        identifier: identifier.trim(),
        password,
        captchaToken: turnstileToken || undefined,
      });

      if (res.error) {
        if (res.error.toLowerCase().includes("email not confirmed")) {
          setEmailNotConfirmed(true);
        } else {
          setError(res.error);
        }
        if (turnstileWidgetId.current && window.turnstile) {
          window.turnstile.reset(turnstileWidgetId.current);
          setTurnstileToken("");
        }
        return;
      }

      if (res.session) {
        await supabase.auth.setSession(res.session);
      }

      const params = new URLSearchParams(window.location.search);
      const nextParam = params.get("next");
      const target = nextParam && nextParam.startsWith("/") && !nextParam.startsWith("//") ? nextParam : "/dashboard";
      router.replace(target);
      router.refresh();
    } catch {
      setError("Could not log in. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  };

  const resendConfirmation = async () => {
    setResendLoading(true);
    setResendDone(false);
    try {
      const res = await resendConfirmationEmail({
        identifier: identifier.trim(),
      });
      if (res.error) {
        setError(res.error);
      } else {
        setResendDone(true);
      }
    } catch {
      setError("Could not resend. Check your connection and try again.");
    } finally {
      setResendLoading(false);
    }
  };

  return (
    <main style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", padding: 24,
                   background: "radial-gradient(circle at 50% -10%, rgba(255, 255, 255, .12), var(--auth-shell, #08090b) 60%)",
                   fontFamily: "Outfit, Arial, sans-serif" }}>
      <div style={{ width: "min(400px,100%)", background: "var(--auth-card, #0e1015)", border: "1px solid var(--auth-card-border, rgba(0, 0, 0, .08))", borderRadius: 16, padding: 28, boxShadow: "0 20px 50px rgba(0,0,0,.45)" }}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 20 }}>
          <Link href="/" aria-label={`${SITE_NAME} home`} style={{ display: "inline-flex", alignItems: "center", gap: 9, textDecoration: "none", color: "var(--auth-text, #000)", fontWeight: 600, fontSize: 20 }}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/addons/logo.svg" alt="" width={26} height={26} />
            <span>{SITE_NAME}</span>
          </Link>
        </div>
        {forgotMode ? (
          <div>
            <h1 style={{ fontFamily: "Unbounded, sans-serif", fontSize: 22, fontWeight: 500, letterSpacing: "-0.5px", margin: "0 0 8px", color: "var(--auth-text, #000)" }}>
              Reset password
            </h1>
            <p style={{ color: "var(--auth-muted, #0e0505)", fontSize: 13, margin: "0 0 20px", lineHeight: 1.5 }}>
              Enter your username or email address and we&apos;ll send you a link to reset your password.
            </p>

            {resetSent ? (
              <div style={{ padding: "14px 16px", borderRadius: 10, background: "var(--auth-good-bg, rgba(222, 131, 131, .08))", border: "1px solid rgba(222, 131, 131, .2)", marginBottom: 18 }}>
                <p style={{ margin: "0 0 6px", color: "var(--auth-good, #de8383)", fontSize: 13, fontWeight: 600, display: "flex", alignItems: "center", gap: 7 }}>
                  <MailCheck size={16} /> Check your inbox
                </p>
                <p style={{ margin: 0, color: "var(--auth-good-text, #440d0d)", fontSize: 12, lineHeight: 1.5 }}>
                  If an account exists for <strong style={{ color: "var(--auth-text, #000)" }}>{identifier}</strong>, we sent a password reset link. Click the link in the email to set a new password.
                </p>
              </div>
            ) : (
              <>
                <label className="lbl">Username or email</label>
                <input
                  className="field"
                  type="text"
                  autoCapitalize="none"
                  autoCorrect="off"
                  spellCheck="false"
                  value={identifier}
                  onChange={(e) => setIdentifier(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && submitReset()}
                  placeholder="pluto or you@example.com"
                />

                {error && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 13, marginTop: 12 }}>{error}</p>}

                <button
                  className="btn"
                  onClick={submitReset}
                  disabled={resetLoading}
                  style={{ background: "var(--auth-accent, #ffffff)", color: "var(--auth-accent-text, #604a4a)", width: "100%", marginTop: 18 }}
                >
                  {resetLoading ? "Sending reset link…" : "Send reset link"}
                </button>
              </>
            )}

            <div style={{ marginTop: 18, textAlign: "center" }}>
              <button
                type="button"
                onClick={() => { setForgotMode(false); setError(""); setResetSent(false); }}
                style={{ background: "none", border: "none", color: "var(--auth-accent, #ebbdbd)", fontSize: 13, fontWeight: 600, cursor: "pointer", padding: 0 }}
              >
                Back to sign in
              </button>
            </div>
          </div>
        ) : (
          <div>
            <h1 style={{ fontFamily: "Unbounded, sans-serif", fontSize: 20, fontWeight: 500, letterSpacing: "-0.5px", margin: "0 0 20px", color: "var(--auth-text, #000)", textAlign: "center" }}>
              Welcome back to {SITE_NAME}
            </h1>

            <DiscordButton />
            <GoogleButton mode="login" />
            <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "16px 0", color: "var(--auth-muted, #000)", fontSize: 12 }}>
              <div style={{ flex: 1, height: 1, background: "var(--auth-line, #2e2222)" }} /> or continue with <div style={{ flex: 1, height: 1, background: "var(--auth-line, #2e2222)" }} />
            </div>

            {notice && (
              <p style={{ color: "var(--auth-good, #de8383)", fontSize: 13, marginBottom: 14, display: "flex", gap: 8, alignItems: "center" }}>
                <MailCheck size={16} /> {notice}
              </p>
            )}

            <label className="lbl">Username or email</label>
            <input
              className="field"
              type="text"
              autoCapitalize="none"
              autoCorrect="off"
              spellCheck="false"
              value={identifier}
              onChange={(e) => setIdentifier(e.target.value)}
              placeholder="pluto or you@example.com"
            />

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14 }}>
              <label className="lbl" style={{ margin: 0 }}>Password</label>
              <button
                type="button"
                onClick={() => { setForgotMode(true); setError(""); }}
                style={{ background: "none", border: "none", color: "var(--auth-accent, #f5caca)", fontSize: 12, cursor: "pointer", padding: 0 }}
              >
                Forgot password?
              </button>
            </div>
            <div style={{ position: "relative" }}>
              <input
                className="field"
                type={showPassword ? "text" : "password"}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                style={{ paddingRight: 40 }}
                onKeyDown={(e) => e.key === "Enter" && submit()}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                aria-label={showPassword ? "Hide password" : "Show password"}
                title={showPassword ? "Hide password" : "Show password"}
                style={{
                  position: "absolute",
                  right: 10,
                  top: "50%",
                  transform: "translateY(-50%)",
                  background: "none",
                  border: "none",
                  color: "var(--auth-muted, #0e0505)",
                  cursor: "pointer",
                  padding: 4,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>

            <div ref={turnstileContainer} style={{ display: "flex", justifyContent: "center", minHeight: turnstileSiteKey ? 65 : 0, marginTop: turnstileSiteKey ? 14 : 0 }} />
            {turnstileError && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 12, margin: "8px 0 0" }}>{turnstileError}</p>}

            {emailNotConfirmed && (
              <div style={{ marginTop: 12, padding: "12px 14px", border: "1px solid #573d3d", borderRadius: 9, background: "var(--auth-good-bg, rgba(222, 131, 131, .07))" }}>
                <p style={{ margin: "0 0 8px", color: "var(--auth-good, #de8383)", fontSize: 13, fontWeight: 600, display: "flex", alignItems: "center", gap: 7 }}>
                  <MailCheck size={15} /> Email not confirmed
                </p>
                <p style={{ margin: "0 0 10px", color: "var(--auth-good-text, #440d0d)", fontSize: 12 }}>
                  Check your inbox for a confirmation link. If you didn&apos;t receive it, resend it below.
                </p>
                {resendDone ? (
                  <p style={{ margin: 0, color: "var(--auth-good, #de8383)", fontSize: 12, fontWeight: 600 }}>Confirmation email sent. Check your inbox.</p>
                ) : (
                  <button
                    type="button"
                    onClick={() => void resendConfirmation()}
                    disabled={resendLoading}
                    style={{ background: "transparent", border: "1px solid #472727", borderRadius: 6, color: "var(--auth-good, #de8383)", fontSize: 12, fontWeight: 700, padding: "6px 12px", cursor: resendLoading ? "wait" : "pointer", opacity: resendLoading ? 0.6 : 1 }}
                  >
                    {resendLoading ? "Sending…" : "Resend confirmation email"}
                  </button>
                )}
              </div>
            )}

            {error && <p style={{ color: "var(--auth-bad, #f8d6d6)", fontSize: 13, marginTop: 12 }}>{error}</p>}

            <button className="btn" onClick={submit} disabled={loading || (Boolean(turnstileSiteKey) && !turnstileToken)}
                    style={{ background: "var(--auth-accent, #ffffff)", color: "var(--auth-accent-text, #604a4a)", width: "100%", marginTop: 18 }}>
              {loading ? "Logging in…" : "Log in"}
            </button>

            <p style={{ marginTop: 18, fontSize: 14, color: "var(--auth-muted, #1a0a0a)", textAlign: "center" }}>
              New to {SITE_NAME}? <Link href="/signup" style={{ fontWeight: 600 }}>Choose your name</Link>
            </p>
          </div>
        )}
      </div>
    </main>
  );
}
