"use client";

import { Loader2 } from "lucide-react";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { getPlayerMe } from "@/api/player";
import { postPlayerAuthLogin } from "@/api/player-auth";
import { getPublicCurrencies } from "@/api/currency";
import { LanguageSwitcher } from "@/components/language-switcher";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { usePlayerSessionStore } from "@/stores/player-session-store";
import {
  validatePlayerLoginPassword,
  validatePlayerLoginUsername,
} from "@/lib/player-input-validation";
import { LotteryApiBizError } from "@/types/api/errors";

function stripSearchParamFromBrowserUrl(name: string): void {
  if (typeof window === "undefined") return;
  const url = new URL(window.location.href);
  if (!url.searchParams.has(name)) return;
  url.searchParams.delete(name);
  const next = `${url.pathname}${url.search}${url.hash}`;
  window.history.replaceState(null, "", next);
}

export function PlayerLoginScreen(): React.ReactElement {
  const { t } = useTranslation("entry");
  const router = useRouter();
  const searchParams = useSearchParams();
  const setBearerToken = usePlayerSessionStore((s) => s.setBearerToken);
  const setProfile = usePlayerSessionStore((s) => s.setProfile);
  const clearBearerToken = usePlayerSessionStore((s) => s.clearBearerToken);
  const sessionExpiredHandled = useRef(false);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (sessionExpiredHandled.current) return;
    if (searchParams.get("session") !== "expired") return;

    sessionExpiredHandled.current = true;
    clearBearerToken();
    toast.error(t("errors.sessionExpired"));
    stripSearchParamFromBrowserUrl("session");
  }, [clearBearerToken, searchParams, t]);

  async function handleSubmit(event: React.FormEvent): Promise<void> {
    event.preventDefault();
    if (!username.trim() || !password) {
      toast.error(t("login.missingFields"));
      return;
    }

    const usernameIssue = validatePlayerLoginUsername(username);
    if (usernameIssue === "invalid_charset") {
      toast.error(
        t("login.usernameInvalidCharset", {
          defaultValue: "账号只能使用字母、数字、点（.）、下划线和连字符",
        }),
      );
      return;
    }

    const passwordIssue = validatePlayerLoginPassword(password);
    if (passwordIssue === "too_short") {
      toast.error(
        t("login.passwordMinLength", { defaultValue: "密码至少需要 6 个字符" }),
      );
      return;
    }

    setLoading(true);
    try {
      const data = await postPlayerAuthLogin({
        username: username.trim(),
        password,
      });
      setBearerToken(data.access_token);
      const me = await getPlayerMe();
      setProfile(me);
      try {
        const currencies = await getPublicCurrencies();
        usePlayerSessionStore.getState().setCurrencies(currencies.items);
      } catch {
        // 不阻断登录
      }
      router.replace("/hall");
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("login.failed"));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="relative flex min-h-dvh flex-col bg-white">
      <div className="relative h-[45vh] min-h-[320px] shrink-0 overflow-hidden bg-red-600">
        <div className="pointer-events-none absolute inset-0">
          <Image src="/entry/image1.png" alt="" fill className="object-cover object-center" priority />
        </div>
        <div className="absolute left-0 right-0 top-0 z-20 flex items-center px-4 py-3">
          <LanguageSwitcher variant="header" showFlag={false} />
        </div>
      </div>

      <div className="mx-auto w-full max-w-md flex-1 px-4 py-8">
        <h1 className="text-xl font-bold text-gray-900">
          {t("login.title")}
        </h1>
        <p className="mt-2 text-sm text-muted-foreground">
          {t("login.hint")}
        </p>

        <form className="mt-6 space-y-4" onSubmit={(e) => void handleSubmit(e)}>
          <div className="space-y-1">
            <Label htmlFor="login-user">{t("login.username")}</Label>
            <Input
              id="login-user"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              autoComplete="username"
            />
          </div>
          <div className="space-y-1">
            <Label htmlFor="login-pass">{t("login.password")}</Label>
            <Input
              id="login-pass"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
            />
          </div>
          <Button type="submit" className="w-full bg-red-600 hover:bg-red-700" disabled={loading}>
            {loading ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
            {t("login.submit")}
          </Button>
        </form>
      </div>
    </div>
  );
}
