import { useState } from "react";
import { motion } from "framer-motion";
import { Tv, User, KeyRound, Loader2, ArrowLeft } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/hooks/useAuth";
import LanguageSelect from "@/components/LanguageSelect";
import {
  FocusableButton,
  FocusableSection,
  FocusableInput,
} from "@/components/focusable";
import { recoverFocus } from "@/hooks/useFocusWatchdog";

const Login = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { login } = useAuth();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e?: React.FormEvent | undefined) => {
    e?.preventDefault?.();
    if (submitting) return;
    if (!username || !password) return;
    setError(null);
    setSubmitting(true);
    try {
      const user = await login(username.trim(), password);
      await new Promise((r) => setTimeout(r, 100));
      if (user?.role === "admin") navigate("/admin");
      else navigate("/", { replace: true });
    } catch (err: unknown) {
      console.error("[Login] handleSubmit error:", err);
      const msg =
        err instanceof Error
          ? err.message
          : typeof err === "string"
            ? err
            : "Login failed. Check your credentials and try again.";
      setError(msg);
    } finally {
      setSubmitting(false);
      // Samsung QA v1.4.2 — HARD FOCUS RESET. After every async login
      // attempt (success OR failure), explicitly re-anchor focus on
      // a known interactive element so Tizen's focus engine can't end
      // up pointing at an unmounted node.
      window.setTimeout(() => {
        recoverFocus(["login-submit", "login-username", "login-back"]);
      }, 50);
    }
  };

  return (
    <FocusableSection
      focusKey="login-page"
      autoFocus
      data-testid="login-page"
      className="relative h-screen w-full overflow-hidden flex items-center justify-center px-4 py-6 sm:py-10"
    >
      <div
        className="absolute inset-0 bg-cover bg-center bg-no-repeat"
        style={{ backgroundImage: "url('/images/nebula-bg.png')" }}
      />
      <div className="absolute inset-0 bg-background/60" />

      <FocusableButton
        focusKey="login-back"
        data-testid="login-back-btn"
        onEnter={() => navigate("/welcome")}
        onClick={() => navigate("/welcome")}
        className="absolute z-20 top-4 sm:top-6 start-4 sm:start-6 w-10 h-10 sm:w-11 sm:h-11 rounded-full glass flex items-center justify-center text-muted-foreground hover:text-foreground hover:border-primary/40 transition-colors outline-none"
      >
        <ArrowLeft className="w-5 h-5 rtl:rotate-180" />
      </FocusableButton>

      <div className="absolute z-20 top-4 sm:top-6 end-4 sm:end-6">
        <LanguageSelect align="right" />
      </div>

      {/* Form container — wrapped in its own FocusableSection so
          the inputs + submit button form a self-contained focus
          cluster (Username → Password → Sign In). */}
      <FocusableSection
        focusKey="login-form"
        autoFocus
        as="form"
        className="relative z-10 glass-card rounded-2xl sm:rounded-3xl p-5 sm:p-8 w-full max-w-[360px] sm:max-w-md"
        onSubmit={(e) => {
          // FocusableSection forwards <form>'s onSubmit through `rest`.
          void handleSubmit(e as unknown as React.FormEvent);
        }}
      >
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, ease: "easeOut" }}
        >
          <div className="flex flex-col items-center mb-6">
            <div
              className="w-14 h-14 sm:w-16 sm:h-16 rounded-2xl glass flex items-center justify-center mb-3"
              style={{
                border: "1px solid hsla(40, 80%, 55%, 0.4)",
                boxShadow: "0 0 40px hsla(40, 80%, 55%, 0.3)",
              }}
            >
              <Tv
                className="w-7 h-7 sm:w-8 sm:h-8 text-primary gold-glow"
                strokeWidth={1.4}
              />
            </div>
            <h1 className="font-display text-xl sm:text-2xl tracking-[0.3em] gold-text">
              NADIPLAYER
            </h1>
            <p className="text-muted-foreground text-[10px] sm:text-xs tracking-[0.25em] uppercase mt-2 text-center">
              {t("login.subtitle")}
            </p>
          </div>

          <div className="space-y-3">
            <FocusableInput
              focusKey="login-username"
              type="text"
              value={username}
              onChange={setUsername}
              placeholder={t("login.username")}
              icon={
                <User className="w-5 h-5 text-muted-foreground shrink-0" />
              }
              testId="login-username-input"
              autoFocusOnMount
              autoComplete="username"
              onArrowDownFocusKey="login-password"
            />
            <FocusableInput
              focusKey="login-password"
              type="password"
              value={password}
              onChange={setPassword}
              placeholder={t("login.password")}
              icon={
                <KeyRound className="w-5 h-5 text-muted-foreground shrink-0" />
              }
              testId="login-password-input"
              autoComplete="current-password"
              onArrowUpFocusKey="login-username"
              onArrowDownFocusKey="login-submit"
              onSubmit={() => {
                void handleSubmit();
              }}
            />
          </div>

          {error && (
            <div
              data-testid="login-error"
              className="mt-4 text-destructive text-xs bg-destructive/10 border border-destructive/30 rounded-lg px-3 py-2"
            >
              {error}
            </div>
          )}

          <FocusableButton
            focusKey="login-submit"
            type="submit"
            loading={submitting}
            disabled={!username || !password}
            fallbackFocusKey="login-password"
            data-testid="login-submit-btn"
            onEnter={() => handleSubmit()}
            onClick={() => handleSubmit()}
            className="w-full mt-6 py-3 rounded-xl bg-gradient-to-r from-primary/80 to-primary/60 text-primary-foreground font-medium text-sm hover:from-primary hover:to-primary/80 transition-all flex items-center justify-center gap-2 disabled:opacity-60 outline-none"
          >
            {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
            {submitting ? t("login.submitting") : t("login.submit")}
          </FocusableButton>

          <p className="mt-5 text-center text-muted-foreground text-[10px] sm:text-[11px] tracking-wide">
            {t("login.contactAdmin")}
          </p>
        </motion.div>
      </FocusableSection>
    </FocusableSection>
  );
};

export default Login;
