"use client";

import { useEffect, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Icon } from "@/components/Icon";
import { api, ensureCsrf } from "@/lib/client";
import Image from "next/image";
import { LanguageToggle, ThemeToggle, useT } from "@/components/providers";

export default function LoginPage() {
  const router = useRouter();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const { t } = useT();

  useEffect(() => {
    void ensureCsrf();
  }, []);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setNotice(null);
    setSubmitting(true);
    try {
      await ensureCsrf();
      const res = await api<{ user: { mustChangePassword: boolean } }>("/api/auth/login", "POST", {
        username: username.trim(),
        password,
      });
      if (res.status === 200) {
        if (res.data?.user?.mustChangePassword) {
          setNotice("تم تسجيل الدخول — يلزم تغيير كلمة المرور المؤقتة أولًا");
          router.push("/dashboard/profile?must_change=1");
        } else {
          router.push("/dashboard");
        }
        router.refresh();
        return;
      }
      setError(res.error ?? "تعذر تسجيل الدخول");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-screen lg:grid lg:grid-cols-2">
      {/* Identity panel */}
      <section className="auth-backdrop relative flex flex-col justify-between overflow-hidden px-8 py-10 text-white sm:px-12 lg:px-16 lg:py-14">
        <div className="absolute -top-24 -left-24 h-72 w-72 rounded-full bg-bousla-500/20 blur-3xl" />
        <div className="absolute bottom-10 -left-10 h-56 w-56 rounded-full bg-sand-500/10 blur-2xl" />
        <div className="relative flex items-center justify-between gap-3">
          <div className="flex items-center gap-3">
          <span className="h-12 w-12 overflow-hidden rounded-xl bg-[#f3efe6] ring-1 ring-sand-400/50">
            <Image src="/logo.png" alt="بوصلة" width={48} height={48} className="h-full w-full object-cover" priority />
          </span>
          <div>
            <p className="text-xl font-bold leading-tight">{t.common.appName}</p>
            <p className="text-xs text-sand-400">{t.common.tagline}</p>
          </div>
          </div>
          <div className="flex items-center gap-1 rounded-lg bg-white/5 ring-1 ring-white/10">
            <ThemeToggle />
            <LanguageToggle />
          </div>
        </div>
        <div className="relative mt-10 max-w-md lg:mt-0">
          <h1 className="text-3xl font-extrabold leading-snug sm:text-4xl">
            {t.login.heroTitle}
            <span className="block text-bousla-300">{t.login.orgFull}</span>
          </h1>
          <p className="mt-5 text-sm leading-7 text-bousla-100/70">
            {t.login.heroSub}
          </p>
          <ul className="mt-8 grid gap-3 text-sm text-bousla-100/80">
            {t.login.benefits.map((line) => (
              <li key={line} className="flex items-start gap-2">
                <Icon name="check" className="mt-0.5 h-4 w-4 shrink-0 text-bousla-300" />
                <span>{line}</span>
              </li>
            ))}
          </ul>
        </div>
        <p className="relative mt-10 text-[11px] text-white/40 lg:mt-0">
          جميع الحقوق محفوظة — {t.login.orgFull}
        </p>
      </section>

      {/* Login form */}
      <section className="flex items-center justify-center bg-slate-100 px-6 py-14 sm:px-10">
        <div className="w-full max-w-md">
          <div className="mb-8 text-center lg:hidden">
            <span className="mx-auto h-14 w-14 overflow-hidden rounded-xl bg-[#f3efe6] ring-1 ring-sand-400/50">
              <Image src="/logo.png" alt="بوصلة" width={56} height={56} className="h-full w-full object-cover" />
            </span>
            <h2 className="mt-3 text-xl font-bold text-slate-900">{t.common.appName}</h2>
          </div>
          <div className="rounded-2xl bg-white p-7 shadow-card sm:p-9">
            <h2 className="text-2xl font-extrabold text-slate-900">{t.login.welcome}</h2>
            <p className="mt-1 text-sm text-slate-500">{t.login.subtitle}</p>

            {error && (
              <div role="alert" className="mt-5 flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 px-3.5 py-2.5 text-sm text-red-700">
                <Icon name="xmark" className="mt-0.5 h-4 w-4 shrink-0" />
                <span>{error}</span>
              </div>
            )}
            {notice && (
              <div className="mt-5 flex items-start gap-2 rounded-lg border border-bousla-200 bg-bousla-50 px-3.5 py-2.5 text-sm text-bousla-800">
                <Icon name="check" className="mt-0.5 h-4 w-4 shrink-0" />
                <span>{notice}</span>
              </div>
            )}

            <form onSubmit={onSubmit} className="mt-6 space-y-5" noValidate>
              <div>
                <label htmlFor="username" className="mb-1.5 block text-sm font-semibold text-slate-700">
                  {t.login.username}
                </label>
                <input
                  id="username"
                  name="username"
                  type="text"
                  autoComplete="username"
                  dir="ltr"
                  required
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  className="w-full rounded-lg border border-slate-300 bg-white px-3.5 py-2.5 text-left text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100"
                  placeholder="username"
                />
              </div>
              <div>
                <label htmlFor="password" className="mb-1.5 block text-sm font-semibold text-slate-700">
                  {t.login.password}
                </label>
                <div className="relative">
                  <input
                    id="password"
                    name="password"
                    type={showPassword ? "text" : "password"}
                    autoComplete="current-password"
                    dir="ltr"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full rounded-lg border border-slate-300 bg-white py-2.5 pl-3.5 pr-10 text-left text-sm text-slate-900 outline-none transition placeholder:text-slate-400 focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100"
                    placeholder="••••••••••"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((v) => !v)}
                    className="absolute inset-y-0 right-2 my-auto grid h-7 w-7 place-items-center rounded text-slate-400 hover:text-slate-600"
                    aria-label={showPassword ? "إخفاء كلمة المرور" : "إظهار كلمة المرور"}
                  >
                    <Icon name={showPassword ? "lock" : "key"} className="h-4 w-4" />
                  </button>
                </div>
              </div>
              <button
                type="submit"
                disabled={submitting || username.length === 0 || password.length === 0}
                className="w-full rounded-lg bg-bousla-700 px-4 py-2.5 text-sm font-bold text-white shadow-sm transition hover:bg-bousla-800 focus:outline-none focus:ring-2 focus:ring-bousla-300 disabled:cursor-not-allowed disabled:opacity-60"
              >
                {submitting ? t.login.submitting : t.login.submit}
              </button>
            </form>
          </div>
          <p className="mt-6 text-center text-xs leading-6 text-slate-400">
            {t.login.noSelfSignup}
            <br />
            {t.login.lostAccess} <Link href="/login" className="text-bousla-700 underline underline-offset-2">{t.login.contactAdmin}</Link>.
          </p>
        </div>
      </section>
    </main>
  );
}
