import { useState, type FormEvent } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "wouter";
import { useForgotPassword } from "@workspace/api-client-react";
import { useAppName, useAppSettings } from "@/hooks/use-app-settings";
import i18n from "@/i18n";
import { Loader2, AlertCircle, CheckCircle2, ArrowLeft } from "lucide-react";
import { AnimatedArt } from "@/components/animated-art";

export default function ForgotPasswordPage() {
  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 [identifier, setIdentifier] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);

  const forgot = useForgotPassword();

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    if (!identifier.trim()) {
      setError(t("auth.forgot.errRequired"));
      return;
    }
    setError(null);
    forgot.mutate(
      { data: { identifier: identifier.trim() } },
      {
        onSuccess: () => setSubmitted(true),
        onError: () => setError(t("auth.forgot.errGeneric")),
      },
    );
  };

  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}>
      <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>

      <div className="hidden lg:block lg:w-1/2 relative overflow-hidden shrink-0">
        <AnimatedArt />
      </div>

      <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">
            <h1 className="text-xl font-bold mb-1">{t("auth.forgot.title")}</h1>
            <p className="text-sm text-muted-foreground mb-5">
              {t("auth.forgot.subtitle")}
            </p>

            {!submitted ? (
              <form onSubmit={handleSubmit} className="space-y-5" noValidate>
                <div className="space-y-1.5">
                  <label
                    htmlFor="identifier"
                    className="block font-semibold text-sm text-foreground"
                  >
                    {t("auth.forgot.identifier")}
                  </label>
                  <input
                    id="identifier"
                    type="text"
                    autoComplete="username"
                    value={identifier}
                    onChange={(e) => {
                      setIdentifier(e.target.value);
                      setError(null);
                    }}
                    disabled={forgot.isPending}
                    placeholder={t("auth.forgot.identifierPlaceholder")}
                    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>

                {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>
                )}

                <button
                  type="submit"
                  disabled={forgot.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"
                >
                  {forgot.isPending && (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  )}
                  {forgot.isPending
                    ? t("auth.forgot.sending")
                    : t("auth.forgot.submit")}
                </button>
              </form>
            ) : (
              <div className="space-y-4">
                <div className="flex items-start gap-2 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3 py-2.5 text-sm text-emerald-700 dark:text-emerald-300">
                  <CheckCircle2 className="h-4 w-4 shrink-0 mt-0.5" />
                  <span>{t("auth.forgot.successMessage")}</span>
                </div>
                <p className="text-xs text-muted-foreground">
                  {t("auth.forgot.adminNotice")}
                </p>
              </div>
            )}

            <div className="text-center text-sm text-muted-foreground pt-5">
              <button
                type="button"
                onClick={() => setLocation("/login")}
                className="inline-flex items-center gap-1 text-primary font-semibold hover:underline"
              >
                <ArrowLeft
                  className={`h-3.5 w-3.5 ${dir === "rtl" ? "rotate-180" : ""}`}
                />
                {t("auth.forgot.backToLogin")}
              </button>
            </div>
          </div>
        </div>

        {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>
  );
}
