"use client";

import Link from "next/link";
import { signIn } from "next-auth/react";
import { Eye, EyeOff, LockKeyhole, Mail, Phone, Send, UserRound } from "lucide-react";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { registerCustomer } from "@/app/store/auth/actions";
import { usePreferences } from "@/components/providers/app-providers";
import { useStore } from "./store-provider";

type Mode = "login" | "register";

export function StoreAuthForm({ mode, callbackUrl = "/checkout" }: { mode: Mode; callbackUrl?: string }) {
  const router = useRouter();
  const { dictionary: t } = usePreferences();
  const { href } = useStore();
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();
  const copy = t.store.auth;

  function destination() {
    const safe = callbackUrl.startsWith("/") && !callbackUrl.startsWith("//") ? callbackUrl : "/checkout";
    return safe.startsWith("/store") ? safe : href(safe);
  }

  function submit(formData: FormData) {
    setError(null);
    startTransition(async () => {
      const email = String(formData.get("email") ?? "").trim().toLowerCase();
      const password = String(formData.get("password") ?? "");
      if (mode === "register") {
        const result = await registerCustomer({
          name: String(formData.get("name") ?? ""),
          email,
          phone: String(formData.get("phone") ?? ""),
          password,
        });
        if (!result.ok) {
          const errors = {
            INVALID_INPUT: copy.invalidInput,
            INVALID_PHONE: copy.invalidPhone,
            EMAIL_EXISTS: copy.emailExists,
            PHONE_EXISTS: copy.phoneExists,
            FAILED: copy.failed,
          };
          setError(errors[result.error]);
          return;
        }
      }

      try {
        const result = await signIn("customer-credentials", { email, password, redirect: false });
        if (result?.error) {
          setError(copy.invalidCredentials);
          return;
        }
        router.replace(destination());
        router.refresh();
      } catch {
        setError(copy.failed);
      }
    });
  }

  return (
    <section className="store-auth-card">
      <div className="store-auth-icon"><UserRound size={28} /></div>
      <h1>{mode === "login" ? copy.loginTitle : copy.registerTitle}</h1>
      <p>{mode === "login" ? copy.loginDescription : copy.registerDescription}</p>
      <form action={submit} className="store-auth-form">
        {mode === "register" ? (
          <label><span>{copy.name}</span><span className="store-field"><UserRound size={18} /><input name="name" placeholder={copy.namePlaceholder} required autoComplete="name" /></span></label>
        ) : null}
        <label><span>{copy.email}</span><span className="store-field"><Mail size={18} /><input dir="ltr" name="email" placeholder={copy.emailPlaceholder} required type="email" autoComplete="email" /></span></label>
        {mode === "register" ? (
          <label><span>{copy.phone}</span><span className="store-field"><Phone size={18} /><input dir="ltr" name="phone" placeholder={copy.phonePlaceholder} required inputMode="tel" autoComplete="tel" /></span></label>
        ) : null}
        <label>
          <span>{copy.password}</span>
          <span className="store-field">
            <LockKeyhole size={18} />
            <input dir="ltr" minLength={mode === "register" ? 8 : undefined} name="password" placeholder={copy.passwordPlaceholder} required type={showPassword ? "text" : "password"} autoComplete={mode === "login" ? "current-password" : "new-password"} />
            <button onClick={() => setShowPassword((current) => !current)} type="button" aria-label={copy.password}>{showPassword ? <EyeOff size={17} /> : <Eye size={17} />}</button>
          </span>
        </label>
        {error ? <p className="store-form-error" role="alert">{error}</p> : null}
        <button className="store-primary-action full" disabled={pending} type="submit">
          <Send size={17} />{pending ? (mode === "login" ? copy.loggingIn : copy.registering) : (mode === "login" ? copy.login : copy.register)}
        </button>
      </form>
      <div className="store-auth-switch">
        <span>{mode === "login" ? copy.noAccount : copy.hasAccount}</span>
        <Link href={href(mode === "login" ? "/auth/register" : "/auth/login")}>{mode === "login" ? copy.register : copy.login}</Link>
      </div>
    </section>
  );
}
