"use client";

import Link from "next/link";
import { Eye, EyeOff, Lock, LogIn, User } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { FormEvent, useEffect, useState } from "react";

import { AppLogo } from "@/components/branding/app-logo";
import { LanguageSwitcher } from "@/components/layout/language-switcher";
import { useLocale } from "@/components/providers/locale-provider";

const REMEMBERED_IDENTITY_KEY = "abelbirdnest_remembered_identity";

export function LoginClient() {
  const { dict } = useLocale();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [identity, setIdentity] = useState("");
  const [password, setPassword] = useState("");
  const [rememberDevice, setRememberDevice] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [helperEmail, setHelperEmail] = useState("");
  const [helperSubmitting, setHelperSubmitting] = useState<"reset" | "verify" | null>(null);
  const [helperMessage, setHelperMessage] = useState<string | null>(null);

  useEffect(() => {
    const rememberedIdentity = window.localStorage.getItem(REMEMBERED_IDENTITY_KEY);

    if (rememberedIdentity) {
      setIdentity(rememberedIdentity);
      setRememberDevice(true);
    }
  }, []);

  async function submitHelper(type: "reset" | "verify") {
    setHelperSubmitting(type);
    setHelperMessage(null);
    setError(null);

    try {
      const response = await fetch(
        type === "reset" ? "/api/v1/auth/forgot-password" : "/api/v1/auth/resend-verification",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email: helperEmail })
        }
      );

      const payload = (await response.json()) as {
        message?: string;
        errors?: Record<string, string[]>;
      };

      if (!response.ok) {
        const firstError = payload.errors ? Object.values(payload.errors)[0]?.[0] : undefined;
        throw new Error(firstError ?? payload.message ?? dict.common.requestFailed);
      }

      setHelperMessage(payload.message ?? dict.common.sendSuccess);
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.common.requestFailed);
    } finally {
      setHelperSubmitting(null);
    }
  }

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const response = await fetch("/api/v1/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          identity,
          password,
          remember_me: rememberDevice
        })
      });

      const payload = (await response.json()) as {
        message?: string;
        errors?: Record<string, string[]>;
        data?: {
          redirect_to?: string;
        };
      };

      if (!response.ok) {
        const firstError = payload.errors
          ? Object.values(payload.errors)[0]?.[0]
          : undefined;
        throw new Error(firstError ?? payload.message ?? dict.common.requestFailed);
      }

      if (rememberDevice) {
        window.localStorage.setItem(REMEMBERED_IDENTITY_KEY, identity.trim());
      } else {
        window.localStorage.removeItem(REMEMBERED_IDENTITY_KEY);
      }

      const next = searchParams.get("next") || payload.data?.redirect_to || "/dashboard";
      router.push(next);
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.common.requestFailed);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-screen bg-canvas px-6 py-10 lg:h-screen lg:overflow-hidden lg:px-0 lg:py-0">
      <div className="mx-auto grid w-full max-w-7xl gap-10 lg:h-full lg:max-w-none lg:grid-cols-[minmax(0,1fr)_720px] lg:gap-0">
        <section className="hidden lg:flex lg:h-screen lg:items-center lg:justify-center lg:overflow-hidden lg:px-12 xl:px-20">
          <div className="flex w-full max-w-2xl items-center justify-center">
            <div className="w-full">
              <div className="overflow-hidden rounded-xl border border-line/70 bg-gradient-to-br from-[#0b2227] via-[#10353a] to-moss p-10 shadow-panel">
                <div className="flex h-[420px] flex-col justify-center rounded-lg border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(255,255,255,0.12),_transparent_45%)] p-10">
                  <div className="flex items-center gap-4">
                    <AppLogo size={88} className="h-[88px] w-[88px] rounded-2xl object-contain" priority />
                    <div>
                      <h1 className="text-5xl font-black tracking-tight text-[#5cb8e8]">
                        AbelBirdnest
                      </h1>
                      <p className="-mt-2 text-3xl font-bold text-white/55">STOCK</p>
                    </div>
                  </div>
                  <div className="mt-16">
                    <p className="max-w-md text-[18px] leading-8 text-white/80">
                      {dict.login.description}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>

        <section className="flex items-start justify-center lg:h-screen lg:overflow-y-auto lg:border-l lg:border-line/70 lg:bg-white/60 lg:px-10 lg:py-14 xl:px-14">
          <div className="w-full max-w-[560px] rounded-lg border border-line/70 bg-white p-8 shadow-panel sm:p-12">
            <div className="mb-8 flex justify-end">
              <LanguageSwitcher />
            </div>
            <header className="mb-10">
              <h1 className="text-[40px] font-semibold tracking-tight text-ink">
                {dict.login.title}
              </h1>
              <p className="mt-3 text-[18px] leading-8 text-slate-600">
                {dict.login.subtitle}
              </p>
            </header>

            <form className="space-y-6" onSubmit={handleSubmit}>
              <label className="block">
                <span className="ops-label">{dict.login.identity}</span>
                <div className="relative">
                  <User className="pointer-events-none absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                  <input
                    value={identity}
                    onChange={(event) => setIdentity(event.target.value)}
                    className="ops-input pl-11"
                    placeholder="name@company.com"
                    autoComplete="username"
                  />
                </div>
              </label>

              <label className="block">
                <div className="mb-1.5 flex items-center justify-between">
                  <span className="ops-label mb-0">{dict.login.password}</span>
                  <span className="text-[13px] font-semibold text-slate-500">{dict.login.useHelper}</span>
                </div>
                <div className="relative">
                  <Lock className="pointer-events-none absolute left-3 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
                  <input
                    type={showPassword ? "text" : "password"}
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                    className="ops-input pl-11 pr-12"
                    placeholder="••••••••"
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-500"
                    onClick={() => setShowPassword((current) => !current)}
                  >
                    {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
                  </button>
                </div>
              </label>

              <label className="flex items-center gap-3 text-[15px] text-slate-600">
                <input
                  type="checkbox"
                  className="h-4 w-4 rounded border-line/70 text-moss focus:ring-moss"
                  checked={rememberDevice}
                  onChange={(event) => setRememberDevice(event.target.checked)}
                />
                <span>{dict.login.remember}</span>
              </label>

              {error ? (
                <div className="rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">
                  {error}
                </div>
              ) : null}

              <button type="submit" disabled={submitting} className="ops-btn-primary w-full py-3 text-lg">
                <LogIn className="h-5 w-5" />
                {submitting ? dict.common.processing : dict.login.loginNow}
              </button>
            </form>

            <footer className="mt-12 border-t border-line/60 pt-8 text-center">
              <div className="rounded-lg border border-line/70 bg-slate-50 px-4 py-4 text-left">
                <p className="text-sm font-semibold text-ink">{dict.login.helpTitle}</p>
                <p className="mt-2 text-[13px] leading-6 text-slate-600">
                  {dict.login.helpCopy}
                </p>
                <label className="mt-4 block">
                  <span className="ops-label">{dict.login.helpEmail}</span>
                  <input
                    value={helperEmail}
                    onChange={(event) => setHelperEmail(event.target.value)}
                    className="ops-input"
                    placeholder="name@company.com"
                  />
                </label>
                <div className="mt-4 flex flex-wrap gap-3">
                  <button
                    type="button"
                    onClick={() => void submitHelper("reset")}
                    disabled={helperSubmitting !== null}
                    className="ops-btn-secondary"
                  >
                    {helperSubmitting === "reset" ? dict.common.processing : dict.login.sendReset}
                  </button>
                  <button
                    type="button"
                    onClick={() => void submitHelper("verify")}
                    disabled={helperSubmitting !== null}
                    className="ops-btn-secondary"
                  >
                    {helperSubmitting === "verify" ? dict.common.processing : dict.login.resendVerification}
                  </button>
                </div>
                {helperMessage ? (
                  <div className="mt-4 rounded border border-moss/30 bg-moss/10 px-4 py-3 text-sm text-moss">
                    {helperMessage}
                  </div>
                ) : null}
              </div>

              <p className="text-[15px] text-slate-600">
                {dict.login.noAccount}{" "}
                <Link href="/contact-admin" className="font-semibold text-moss hover:underline">
                  {dict.login.contactAdmin}
                </Link>
              </p>
              <div className="mt-8 flex flex-wrap justify-center gap-6 text-[12px] font-bold uppercase tracking-[0.08em] text-slate-500">
                <Link href="/help-public" className="hover:text-moss hover:underline">
                  {dict.login.support}
                </Link>
                <Link href="/privacy-policy" className="hover:text-moss hover:underline">
                  {dict.login.privacy}
                </Link>
                <Link href="/terms-and-conditions" className="hover:text-moss hover:underline">
                  {dict.login.terms}
                </Link>
              </div>
            </footer>
          </div>
        </section>
      </div>

      <div className="pointer-events-none fixed bottom-0 left-0 flex w-full justify-between px-4 py-3 text-[11px] font-bold uppercase tracking-[0.08em] text-slate-400">
        <span>v2.4.0-pro</span>
        <span>© 2026 AbelBirdnest</span>
      </div>
    </main>
  );
}
