"use client";

import { useActionState, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { CheckCircle2, Phone, PhoneCall, X } from "lucide-react";
import { requestCallback, type LeadState } from "@/app/actions";
import { CALLBACK_SLOTS } from "@/lib/lead-schema";
import { INDUSTRY_OPTIONS } from "@/lib/content";
import FloatInput from "./FloatInput";
import FloatDropdown from "./FloatDropdown";
import PhoneInput from "./PhoneInput";

const initial: LeadState = { ok: false, message: "" };

/* Short chip labels — full values are posted so the API is untouched */
const SHORT_SLOTS = ["ASAP", "Morning", "Afternoon", "Evening"] as const;

export default function CallbackModal({ onClose }: { onClose: () => void }) {
  const [state, action, pending] = useActionState(requestCallback, initial);
  const nameRef = useRef<HTMLInputElement>(null);
  // Portal to document.body so centering is relative to the viewport,
  // never to an ancestor stacking context. Render-safe: false on the
  // server, true on the client — no effect needed.
  const [mounted] = useState(() => typeof document !== "undefined");

  // Autofocus + body scroll lock + Escape to close
  useEffect(() => {
    nameRef.current?.focus();
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener("keydown", onKey);
    };
  }, [onClose]);

  if (!mounted) return null;

  return createPortal(
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-navy/60 p-4 sm:p-6"
      role="dialog"
      aria-modal="true"
      aria-label="Request a callback"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="w-full max-w-[580px] rounded-2xl bg-white text-ink">
        {/* Header band */}
        <div className="relative flex items-center gap-4 rounded-t-2xl bg-navy px-6 py-5 sm:px-7">
          <span
            aria-hidden="true"
            className="grid size-11 shrink-0 place-items-center rounded-xl bg-brand"
          >
            <PhoneCall size={22} className="text-white" />
          </span>
          <div className="min-w-0">
            <p className="font-mono text-[10.5px] font-medium tracking-[0.18em] text-brand-light">
              REQUEST A CALLBACK
            </p>
            <h3 className="mt-0.5 font-display text-[22px] font-bold leading-tight text-white">
              We&apos;ll call you back
            </h3>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close"
            className="absolute right-4 top-4 grid size-9 place-items-center rounded-lg text-white/70 hover:bg-white/10 hover:text-white"
          >
            <X size={19} aria-hidden="true" />
          </button>
        </div>

        <div className="px-6 py-5 sm:px-7">
          {state.ok ? (
            <div className="py-2 text-center">
              <span
                aria-hidden="true"
                className="mx-auto grid size-14 place-items-center rounded-full bg-green-50 ring-1 ring-green-200"
              >
                <CheckCircle2 size={28} className="text-green-600" />
              </span>
              <h4 className="mt-4 font-display text-[20px] font-bold">
                Request received!
              </h4>
              <p className="mx-auto mt-2 max-w-[330px] rounded-xl bg-green-50 px-4 py-3 text-[13.5px] font-medium leading-relaxed text-green-800 ring-1 ring-green-200">
                {state.message}
              </p>
              <button
                type="button"
                onClick={onClose}
                className="mt-5 inline-flex min-h-[48px] w-full items-center justify-center rounded-xl bg-navy px-5 text-sm font-semibold text-white hover:bg-brand-dark"
              >
                Done
              </button>
            </div>
          ) : (
            <form
              action={action}
              onSubmit={(e) => {
                if (pending) e.preventDefault();
              }}
            >
              <div className="mb-4 grid grid-cols-2 gap-3 max-sm:grid-cols-1 max-sm:gap-4">
                <FloatInput
                  ref={nameRef}
                  id="cb-name"
                  name="name"
                  type="text"
                  label="Full Name"
                  autoComplete="name"
                  required
                  minLength={2}
                  filter="name"
                  error={state.errors?.name}
                />
                <PhoneInput
                  id="cb-phone"
                  label="Phone"
                  required
                  error={state.errors?.phone}
                />
              </div>

              <div className="mb-4 grid grid-cols-2 gap-3 max-sm:grid-cols-1 max-sm:gap-4">
                <FloatInput
                  id="cb-email"
                  name="email"
                  type="email"
                  label="Work Email"
                  autoComplete="email"
                  error={state.errors?.email}
                />
                <FloatDropdown
                  id="cb-industry"
                  name="industry"
                  label="Industry"
                  options={INDUSTRY_OPTIONS}
                  placeholder="Select industry"
                  required
                  error={state.errors?.industry}
                />
              </div>

              <fieldset className="mb-4">
                <legend className="mb-2 text-[12px] font-semibold">
                  Preferred Time
                </legend>
                <div className="grid grid-cols-4 gap-2 max-sm:grid-cols-2">
                  {CALLBACK_SLOTS.map((o, i) => (
                    <label
                      key={o}
                      title={o}
                      className="flex cursor-pointer items-center justify-center rounded-xl border border-[#d5dce8] px-2 py-2.5 text-center text-[12px] font-semibold text-body transition-colors has-checked:border-brand has-checked:bg-brand-tint has-checked:text-ink hover:border-brand"
                    >
                      <input
                        type="radio"
                        name="slot"
                        value={o}
                        defaultChecked={i === 0}
                        className="sr-only"
                      />
                      {SHORT_SLOTS[i]}
                    </label>
                  ))}
                </div>
              </fieldset>

              {/* Honeypot — hidden from humans */}
              <div aria-hidden="true" className="absolute -left-[9999px] top-auto h-px w-px overflow-hidden">
                <label>
                  Website
                  <input name="website" type="text" tabIndex={-1} autoComplete="off" />
                </label>
              </div>

              <label className="mb-3 flex items-start gap-2 text-xs font-normal text-muted">
                <input
                  name="consent"
                  type="checkbox"
                  required
                  className="mt-0.5 size-4 shrink-0 accent-[#1d4ed8]"
                />
                I agree to be contacted by MxERP about my enquiry.
              </label>

              <div aria-live="polite" className="min-h-[22px] text-[13px]">
                {state.message && (
                  <p className="text-red-600">{state.message}</p>
                )}
              </div>

              <button
                type="submit"
                disabled={pending}
                className="mt-1 flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-brand text-sm font-semibold text-white hover:bg-brand-dark disabled:opacity-60"
              >
                <Phone size={17} aria-hidden="true" />
                {pending ? "Sending…" : "Call me back"}
              </button>
              <p className="mt-2 flex min-h-[44px] flex-wrap items-center justify-center gap-x-1.5 gap-y-1 text-[13.5px] font-semibold text-body">
                Or call now:{" "}
                <a href="tel:+919818993537" className="text-brand hover:underline">
                  +91-9818993537
                </a>
                <span className="font-mono text-[10px] font-medium tracking-[0.1em] text-muted">SALES</span>
                <span aria-hidden="true" className="text-line">·</span>
                <a href="tel:+919899745220" className="text-brand hover:underline">
                  +91-9899745220
                </a>
                <span className="font-mono text-[10px] font-medium tracking-[0.1em] text-muted">SUPPORT</span>
              </p>
            </form>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}
