"use client";

import { useActionState, useEffect, useState } from "react";
import Link from "next/link";
import { useFormStatus } from "react-dom";
import { Eye, EyeOff, Loader2 } from "lucide-react";
import { loginAction, type AuthState } from "@/app/actions/auth";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const initial: AuthState = { status: "idle" };

function Submit({ label, pendingLabel }: { label: string; pendingLabel: string }) {
  const { pending } = useFormStatus();
  return (
    <button
      type="submit"
      disabled={pending}
      className="flex h-12 w-full items-center justify-center gap-2 bg-charcoal text-[12px] uppercase tracking-[0.18em] text-ivory transition-opacity hover:opacity-90 disabled:opacity-60"
    >
      {pending ? (
        <>
          <Loader2 className="h-4 w-4 animate-spin" />
          {pendingLabel}
        </>
      ) : (
        label
      )}
    </button>
  );
}

export function LoginForm({
  locale,
  callbackUrl,
  labels,
  demo,
  registerHref,
  showDemo,
}: {
  locale: string;
  callbackUrl: string;
  labels: {
    title: string;
    description: string;
    email: string;
    password: string;
    login: string;
    loggingIn: string;
    invalid: string;
    noAccount: string;
    createAccount: string;
    demoAccounts: string;
  };
  demo: { email: string; password: string; label: string }[];
  registerHref: string;
  showDemo: boolean;
}) {
  const [state, action] = useActionState(loginAction, initial);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (state.status === "error") {
      setPassword("");
    }
  }, [state]);

  return (
    <div className="border border-line bg-cream p-6 shadow-panel md:p-8">
      <p className="eyebrow">DAR ZELLIGE</p>
      <h1 className="mt-4 font-serif text-4xl font-light tracking-tight">{labels.title}</h1>
      <p className="mt-3 text-[14px] leading-relaxed text-walnut">{labels.description}</p>

      {state.status === "error" && (
        <p className="mt-5 border border-terracotta/30 bg-terracotta/5 px-4 py-3 text-[14px] text-terracotta">
          {state.message ?? labels.invalid}
        </p>
      )}

      <form action={action} className="mt-7 space-y-4">
        <input type="hidden" name="locale" value={locale} />
        <input type="hidden" name="callbackUrl" value={callbackUrl} />
        <div>
          <Label htmlFor="email" className="mb-2 block text-[12px] uppercase tracking-[0.1em] text-walnut">
            {labels.email}
          </Label>
          <Input
            id="email"
            name="email"
            type="email"
            required
            autoComplete="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            className="h-11 bg-cream"
          />
        </div>
        <div>
          <Label htmlFor="password" className="mb-2 block text-[12px] uppercase tracking-[0.1em] text-walnut">
            {labels.password}
          </Label>
          <div className="relative">
            <Input
              id="password"
              name="password"
              type={visible ? "text" : "password"}
              required
              autoComplete="current-password"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              className="h-11 bg-cream pr-11"
            />
            <button
              type="button"
              onClick={() => setVisible((current) => !current)}
              aria-label={visible ? "Hide password" : "Show password"}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-pebble hover:text-charcoal"
            >
              {visible ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </div>
        <Submit label={labels.login} pendingLabel={labels.loggingIn} />
      </form>

      {showDemo && demo.length > 0 && (
        <div className="mt-7 border-t border-line pt-5">
          <p className="text-[12px] font-medium uppercase tracking-[0.12em] text-walnut">{labels.demoAccounts}</p>
          <div className="mt-3 space-y-2">
            {demo.map((account) => (
              <button
                key={account.email}
                type="button"
                onClick={() => {
                  setEmail(account.email);
                  setPassword(account.password);
                }}
                className="flex w-full items-center justify-between gap-3 border border-line bg-parchment/40 px-3 py-2.5 text-left transition-colors hover:border-line-strong hover:bg-parchment"
              >
                <span>
                  <span className="block text-[12px] font-medium uppercase tracking-[0.1em] text-charcoal">
                    {account.label}
                  </span>
                  <span className="text-[13px] text-walnut">{account.email}</span>
                </span>
                <span className="font-mono text-[13px] text-walnut">{account.password}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      <p className="mt-7 text-[14px] text-walnut">
        {labels.noAccount}{" "}
        <Link href={registerHref} className="text-charcoal underline underline-offset-4">
          {labels.createAccount}
        </Link>
      </p>
    </div>
  );
}
