import { useState, type FormEvent } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "wouter";
import { useLogin, getGetMeQueryKey } from "@workspace/api-client-react";
import { useQueryClient } from "@tanstack/react-query";
import { useAppName, useAppSettings } from "@/hooks/use-app-settings";
import i18n from "@/i18n";
import { Eye, EyeOff, Loader2, AlertCircle } from "lucide-react";
import { AnimatedArt } from "@/components/animated-art";

export default function LoginPage() {
  const { t, i18n: i18nInstance } = useTranslation();
  const lang = i18nInstance.language;
  const dir = lang === "ar" ? "rtl" : "ltr";
  const appName = useAppName();
  const { data: settings } = useAppSettings();
  const [, setLocation] = useLocation();
  const queryClient = useQueryClient();

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const login = useLogin();

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    if (!username.trim() || !password) {
      setError(t("auth.errRequired"));
      return;
    }
    setError(null);
    login.mutate(
      { data: { username: username.trim(), password } },
      {
        onSuccess: (user) => {
          if (user.preferredLanguage) {
            i18n.changeLanguage(user.preferredLanguage);
          }
          queryClient.invalidateQueries({ queryKey: getGetMeQueryKey() });
          setLocation("/");
        },
        onError: () => {
          setError(t("auth.errInvalid"));
        },
      },
    );
  };

  const toggleLanguage = () => i18n.changeLanguage(lang === "ar" ? "en" : "ar");

  const footerText =
    lang === "ar" ? settings?.footerTextAr : settings?.footerTextEn;

  return (
    <div className="min-h-screen flex w-full text-foreground relative" dir={dir}>
      {/* Language toggle — outside os-bg so it stays fixed to viewport */}
      <button
        type="button"
        onClick={toggleLanguage}
        className={`absolute top-4 z-50 text-sm font-medium hover:bg-foreground/5 px-3 py-1.5 rounded-md transition-colors text-foreground bg-background/70 backdrop-blur-sm border border-border/50 ${
          dir === "rtl" ? "left-4 md:left-8" : "right-4 md:right-8"
        }`}
      >
        {lang === "ar" ? "EN" : "عربي"}
      </button>

      {/* Animated art panel — hidden on small screens, no logo, no text */}
      <div className="hidden lg:block lg:w-1/2 relative overflow-hidden shrink-0">
        <AnimatedArt />
      </div>

      {/* Form panel */}
      <div className="flex-1 min-w-0 flex flex-col items-center justify-center p-6 sm:p-8 relative os-bg">

        <div className="w-full max-w-[400px]">
          <div className="glass-panel rounded-2xl p-6 sm:p-8">
            <form onSubmit={handleSubmit} className="space-y-5" noValidate>
              {/* Username */}
              <div className="space-y-1.5">
                <label
                  htmlFor="username"
                  className="block font-semibold text-sm text-foreground"
                >
                  {t("auth.username")}
                </label>
                <input
                  id="username"
                  type="text"
                  autoComplete="username"
                  value={username}
                  onChange={(e) => {
                    setUsername(e.target.value);
                    setError(null);
                  }}
                  disabled={login.isPending}
                  className="block w-full h-10 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-60"
                />
              </div>

              {/* Password */}
              <div className="space-y-1.5">
                <label
                  htmlFor="password"
                  className="block font-semibold text-sm text-foreground"
                >
                  {t("auth.password")}
                </label>
                <div className="relative">
                  <input
                    id="password"
                    type={showPassword ? "text" : "password"}
                    autoComplete="current-password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => {
                      setPassword(e.target.value);
                      setError(null);
                    }}
                    disabled={login.isPending}
                    className={`block w-full h-10 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-60 ${
                      dir === "rtl" ? "pl-10" : "pr-10"
                    }`}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    className={`absolute top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors ${
                      dir === "rtl" ? "left-3" : "right-3"
                    }`}
                    aria-label={
                      showPassword
                        ? t("auth.hidePassword")
                        : t("auth.showPassword")
                    }
                  >
                    {showPassword ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </button>
                </div>
                <div
                  className={`flex pt-1 ${
                    dir === "rtl" ? "justify-start" : "justify-end"
                  }`}
                >
                  <button
                    type="button"
                    onClick={() => setLocation("/forgot-password")}
                    className="text-xs text-primary font-medium hover:underline"
                  >
                    {t("auth.forgotPassword")}
                  </button>
                </div>
              </div>

              {/* Error alert */}
              {error && (
                <div
                  role="alert"
                  className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2.5 text-sm text-destructive"
                >
                  <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
                  <span>{error}</span>
                </div>
              )}

              {/* Submit */}
              <button
                type="submit"
                disabled={login.isPending}
                className="w-full inline-flex items-center justify-center gap-2 h-10 rounded-md bg-primary text-primary-foreground font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-60"
              >
                {login.isPending && (
                  <Loader2 className="h-4 w-4 animate-spin" />
                )}
                {login.isPending
                  ? t("auth.signingIn")
                  : t("auth.loginButton")}
              </button>

              {settings?.registrationOpen && (
                <div className="text-center text-sm text-muted-foreground pt-2">
                  {t("auth.noAccount")}{" "}
                  <button
                    type="button"
                    onClick={() => setLocation("/register")}
                    className="text-primary font-semibold hover:underline"
                  >
                    {t("auth.register")}
                  </button>
                </div>
              )}
            </form>
          </div>
        </div>

        {/* Admin-editable footer */}
        {footerText && (
          <div className="absolute bottom-4 inset-x-0 text-center text-xs text-muted-foreground px-4">
            &copy; {new Date().getFullYear()} {appName}. {footerText}
          </div>
        )}
      </div>
    </div>
  );
}
