"use client";

import { ArrowRight, Check } from "lucide-react";
import { useEffect, useRef } from "react";
import { ROLES } from "@/lib/constants";
import { setLocalViewerAction } from "@/app/login/local-actions";
import { FormSubmitButton } from "@/components/ui/form-submit-button";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

type LocalAccessFormProps = {
  scopes: string[];
  error: string | null;
  nextPath?: string;
  role: "admin" | "affiliate";
  setRole: (role: "admin" | "affiliate") => void;
  scope: string;
  setScope: (scope: string) => void;
};

export function LocalAccessForm({
  scopes,
  error,
  nextPath,
  role,
  setRole,
  scope,
  setScope,
}: LocalAccessFormProps) {
  const isAffiliate = role === ROLES.affiliate;
  const showAdminAccess = role === ROLES.admin;
  const previousScopeRef = useRef(scope);

  useEffect(() => {
    if (!isAffiliate || previousScopeRef.current === scope) {
      previousScopeRef.current = scope;
      return;
    }

    previousScopeRef.current = scope;
    const frame = window.requestAnimationFrame(() => {
      document.getElementById("access-password")?.focus();
    });

    return () => window.cancelAnimationFrame(frame);
  }, [isAffiliate, scope]);

  return (
    <form action={setLocalViewerAction} className="mt-7 space-y-8">
      {nextPath ? <input type="hidden" name="next" value={nextPath} /> : null}
      <input type="hidden" name="role" value={role} />
      <input type="hidden" name="scope" value={isAffiliate ? scope : ""} />

      {isAffiliate ? (
        <>
          <div className="space-y-5">
            <div className="flex items-start justify-between gap-3">
              <div>
                <p className="text-[1.1rem] font-semibold tracking-[-0.02em] text-slate-900">Select region</p>
                <p className="mt-1 text-sm text-slate-500">Select your region to continue.</p>
              </div>
              <span className="mt-1 rounded-full border border-[#f1dfcf] bg-[#fff9f3] px-3 py-1 text-xs font-semibold text-[#d9852c] shadow-[0_8px_18px_-16px_rgba(217,133,44,0.5)]">
                {scope}
              </span>
            </div>
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {scopes.map((scopeOption) => {
                const active = scopeOption === scope;
                return (
                  <button
                    key={scopeOption}
                    type="button"
                    onClick={() => setScope(scopeOption)}
                    className={cn(
                      "group rounded-[1.5rem] border px-5 py-4 text-left transition-all duration-200 hover:-translate-y-[2px] active:scale-[0.985] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2663AC] focus-visible:ring-offset-2 motion-reduce:transform-none",
                      active
                        ? "border-[#dfa764] bg-[#fff8f1] text-slate-900 shadow-[0_18px_30px_-20px_rgba(190,126,48,0.3)] ring-1 ring-[#f2d4b0] -translate-y-[1px]"
                        : "border-[#d7e4f2] bg-white text-slate-700 hover:border-[#b9cfe8] hover:bg-[#fcfdff] hover:shadow-[0_14px_24px_-22px_rgba(38,99,172,0.22)]",
                    )}
                    aria-pressed={active}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <span className="block text-[1.75rem] font-black leading-none tracking-[-0.04em]">{scopeOption}</span>
                        <span
                          className={cn(
                            "mt-2.5 block text-xs font-medium",
                            active ? "text-[#cb7a24]" : "text-[#8aa0bc]",
                          )}
                        >
                          {active ? "Current selection" : "Select"}
                        </span>
                      </div>
                      <span
                        className={cn(
                          "inline-flex h-6 w-6 items-center justify-center rounded-full border transition-all duration-200",
                          active
                            ? "border-[#e3b178] bg-[#fff2e0] text-[#cb7a24] shadow-[0_8px_16px_-12px_rgba(203,122,36,0.45)]"
                            : "border-[#d8e4f2] bg-[#f8fbff] text-transparent group-hover:border-[#bfd2e9]",
                        )}
                      >
                        <Check className="h-3.5 w-3.5" />
                      </span>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="rounded-[1.8rem] border border-[#d5e2f1] bg-[linear-gradient(180deg,#ffffff_0%,#fbfdff_100%)] p-4 shadow-[0_22px_36px_-30px_rgba(15,23,42,0.22)] ring-1 ring-white/70">
            <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_240px] md:items-end">
              <div className="space-y-2">
                <label
                  htmlFor="access-password"
                  className="caption text-[11px] uppercase tracking-[0.17em] text-[#6d83a6]"
                >
                  Password
                </label>
                <Input
                  id="access-password"
                  name="access_password"
                  type="password"
                  autoComplete="current-password"
                  placeholder={`Enter ${scope || "region"} password`}
                  className="h-[4.15rem] rounded-[1.25rem] border-[#c9d9ee] bg-white px-4 text-base shadow-none focus-visible:border-[#2663AC] focus-visible:ring-2 focus-visible:ring-[#2663AC]/15"
                />
              </div>
              <FormSubmitButton
                idleLabel="Enter Dashboard"
                pendingLabel="Entering..."
                className="h-[4.25rem] w-full rounded-[1.25rem] bg-[#285f9f] px-8 text-[15px] font-semibold shadow-[0_18px_30px_-22px_rgba(34,89,153,0.62)] transition-all duration-200 hover:-translate-y-[2px] hover:bg-[#214f87] hover:shadow-[0_22px_34px_-24px_rgba(33,79,135,0.68)] focus-visible:ring-2 focus-visible:ring-[#2663AC]/25 motion-reduce:transform-none"
              />
            </div>
            {error ? <p className="mt-4 text-sm font-medium text-rose-600">{error}</p> : null}
          </div>
        </>
      ) : (
        <div className="rounded-[1.9rem] border border-[#dbe6f3] bg-[linear-gradient(180deg,#ffffff_0%,#f8fbff_100%)] p-6">
          <div className="flex items-start justify-between gap-3">
            <div>
              <p className="caption text-[11px] uppercase tracking-[0.17em] text-[#6d83a6]">Admin Access</p>
              <p className="mt-2 text-[1.75rem] font-black leading-none tracking-[-0.04em] text-slate-900">
                Private entry
              </p>
            </div>
            <span className="rounded-full bg-[#eef4fb] px-3 py-1 text-xs font-semibold text-[#2663AC]">
              Private
            </span>
          </div>

          <div className="mt-6 space-y-2">
            <label
              htmlFor="access-password"
              className="caption text-xs uppercase tracking-[0.2em] text-[#6d83a6]"
            >
              Password
            </label>
            <Input
              id="access-password"
              name="access_password"
              type="password"
              autoComplete="current-password"
              placeholder="Enter admin password"
              className="h-[4.15rem] rounded-[1.25rem] border-[#c9d9ee] bg-white px-4 text-base shadow-none focus-visible:border-[#2663AC] focus-visible:ring-2 focus-visible:ring-[#2663AC]/15"
            />
          </div>

          <div className="mt-6 flex flex-wrap items-center gap-3">
            <FormSubmitButton
              idleLabel="Enter Admin"
              pendingLabel="Entering..."
              className="h-[4.15rem] min-w-[240px] rounded-[1.25rem] bg-[#285f9f] px-8 text-base shadow-[0_14px_28px_-22px_rgba(34,89,153,0.58)] transition-colors hover:bg-[#214f87]"
            />
            <button
              type="button"
              onClick={() => setRole(ROLES.affiliate)}
              className="inline-flex h-[4.15rem] items-center gap-2 rounded-[1.25rem] border border-[#d7e4f2] px-5 text-sm font-semibold text-[#2663AC] transition hover:bg-white"
            >
              Regional
              <ArrowRight className="h-4 w-4" />
            </button>
          </div>
          {error ? <p className="mt-4 text-sm font-medium text-rose-600">{error}</p> : null}
        </div>
      )}
    </form>
  );
}
