import { Link } from "@tanstack/react-router";
import { useEffect, useState, type InputHTMLAttributes, type ReactNode } from "react";
import {
  CircleCheck,
  CircleX,
  Eye,
  EyeOff,
  type LucideIcon,
} from "lucide-react";
import { Logo } from "@/components/lotus/Loader";

export type AuthToastData = { type: "success" | "error"; message: string };

export function AuthShell({
  active,
  title,
  children,
}: {
  active: "login" | "register";
  title: string;
  children: ReactNode;
}) {
  return (
    <div className="flex min-h-screen flex-col bg-auth-page font-auth text-foreground">
      <header className="sticky top-0 z-40 w-full border-b border-auth-border bg-auth-header">
        <div className="mx-auto flex max-w-4xl items-center justify-between px-4 py-3">
          <Link to="/" aria-label="Lotus365 home" className="flex items-center">
            <Logo className="text-2xl" />
          </Link>
          <div className="flex items-center gap-2.5">
            <Link
              to="/login"
              className={`rounded-lg px-5 py-2 text-xs font-bold transition md:text-sm ${active === "login" ? "bg-auth-accent text-auth-button-text shadow-md" : "border border-auth-input bg-auth-input text-foreground"}`}
            >
              LOG IN
            </Link>
            <Link
              to="/register"
              className={`rounded-lg px-5 py-2 text-xs font-bold transition md:text-sm ${active === "register" ? "bg-auth-accent text-auth-button-text shadow-md" : "border border-auth-input bg-auth-input text-foreground"}`}
            >
              JOIN NOW
            </Link>
          </div>
        </div>
      </header>
      <main className="mx-auto flex w-full max-w-[440px] flex-1 flex-col justify-center px-4 py-8">
        <h1 className="mb-6 text-center text-2xl font-black uppercase tracking-wider text-foreground md:text-3xl">
          {title}
        </h1>
        <div className="space-y-4">{children}</div>
      </main>
      <footer className="py-3" />
    </div>
  );
}

function IndianFlag() {
  return (
    <svg className="h-3.5 w-5 overflow-hidden rounded-sm" viewBox="0 0 640 480" aria-hidden="true">
      <path fill="var(--color-flag-saffron)" d="M0 0h640v160H0z" />
      <path fill="var(--foreground)" d="M0 160h640v160H0z" />
      <path fill="var(--color-flag-green)" d="M0 320h640v160H0z" />
      <circle cx="320" cy="240" r="40" fill="var(--color-flag-blue)" />
    </svg>
  );
}

const inputClass = "w-full bg-transparent text-sm font-medium text-foreground outline-none placeholder:text-auth-placeholder";

type TextFieldProps = {
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder: string;
  icon?: LucideIcon;
  type?: string;
  inputMode?: InputHTMLAttributes<HTMLInputElement>["inputMode"];
  autoComplete?: string;
  maxLength?: number;
};

export function TextField({
  label,
  value,
  onChange,
  placeholder,
  icon: Icon,
  type = "text",
  inputMode,
  autoComplete,
  maxLength,
}: TextFieldProps) {
  return (
    <div className="flex flex-col justify-center rounded-xl border border-auth-border bg-auth-input px-4 py-2.5">
      <label className="mb-0.5 text-[11px] font-medium text-auth-label">{label}</label>
      <div className="flex items-center gap-2">
        {Icon && <Icon className="size-3 shrink-0 text-auth-label" />}
        <input
          type={type}
          value={value}
          onChange={(event) => onChange(event.target.value)}
          placeholder={placeholder}
          inputMode={inputMode}
          autoComplete={autoComplete}
          maxLength={maxLength}
          className={inputClass}
        />
      </div>
    </div>
  );
}

export function PhoneField({ value, onChange }: { value: string; onChange: (value: string) => void }) {
  return (
    <div className="flex flex-col justify-center rounded-xl border border-auth-border bg-auth-input px-4 py-2.5">
      <label className="mb-0.5 text-[11px] font-medium text-auth-label">Mobile Phone</label>
      <div className="flex items-center gap-2.5">
        <div className="flex items-center gap-1.5 border-r border-auth-border pr-2.5">
          <IndianFlag />
          <span className="text-xs font-bold text-foreground">+91</span>
        </div>
        <input
          type="tel"
          inputMode="numeric"
          autoComplete="tel-national"
          value={value}
          onChange={(event) => onChange(event.target.value.replace(/\D/g, "").slice(0, 10))}
          placeholder="Mobile Phone"
          maxLength={10}
          className={inputClass}
        />
      </div>
    </div>
  );
}

export function PassField({
  value,
  onChange,
  placeholder = "Password",
  label = "Password",
  autoComplete = "current-password",
}: {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  label?: string;
  autoComplete?: string;
}) {
  const [show, setShow] = useState(false);
  return (
    <div className="relative flex flex-col justify-center rounded-xl border border-auth-border bg-auth-input px-4 py-2.5">
      <label className="mb-0.5 text-[11px] font-medium text-auth-label">{label}</label>
      <div className="flex items-center justify-between gap-2">
        <input
          type={show ? "text" : "password"}
          value={value}
          onChange={(event) => onChange(event.target.value)}
          placeholder={placeholder}
          autoComplete={autoComplete}
          className={`${inputClass} pr-8`}
        />
        <button
          type="button"
          aria-label={show ? "Hide password" : "Show password"}
          onClick={() => setShow((visible) => !visible)}
          className="absolute right-4 text-auth-accent transition hover:text-foreground"
        >
          {show ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
        </button>
      </div>
    </div>
  );
}

export function AuthToast({ toast, onClose }: { toast: AuthToastData | null; onClose: () => void }) {
  useEffect(() => {
    if (!toast) return;
    const timer = setTimeout(onClose, 2500);
    return () => clearTimeout(timer);
  }, [toast, onClose]);

  if (!toast) return null;
  const success = toast.type === "success";
  const Icon = success ? CircleCheck : CircleX;
  return (
    <div className="fixed inset-0 z-50 bg-auth-overlay backdrop-blur-[3px]" onClick={onClose}>
      <div
        role="alert"
        onClick={(event) => event.stopPropagation()}
        className={`fixed left-1/2 top-1/2 flex w-[min(90%,360px)] -translate-x-1/2 -translate-y-1/2 flex-col items-center gap-3 rounded-[20px] border border-auth-border border-t-4 bg-auth-panel px-7 py-6 text-center shadow-2xl animate-pop ${success ? "border-t-auth-success" : "border-t-auth-error"}`}
      >
        <Icon className={`size-10 ${success ? "text-auth-success" : "text-auth-error"}`} />
        <p className="text-[15px] font-semibold leading-relaxed text-foreground">{toast.message}</p>
      </div>
    </div>
  );
}
