"use client";

import { useState } from "react";
import { scrollToFirstFormError } from "@/lib/form-utils";
import { validateNonNegativeNumber, validateRequired } from "@/lib/common";
import { clearFieldError, validateEmail } from "@/utils/form-validation";
import Image from "next/image";
import {
  ArrowRight,
  BadgeCheck,
  CalendarClock,
  CheckCircle2,
  Mail,
  ShieldCheck,
  Users,
} from "lucide-react";
import ImmersivePage from "@/components/immersive/ImmersivePage";
import RevealText from "@/components/immersive/RevealText";
import Reveal from "@/components/immersive/Reveal";

const HIGHLIGHTS = [
  {
    number: "01",
    icon: BadgeCheck,
    title: "Open to DIFC & ADGM Firms",
    body: "All registered businesses under DIFC, DFSA, and ADGM regulation are eligible to apply.",
  },
  {
    number: "02",
    icon: CalendarClock,
    title: "12 Months, No Charge",
    body: "Full platform access from day one. No trials, no feature limitations during the programme period.",
  },
  {
    number: "03",
    icon: ShieldCheck,
    title: "Subsidized Continuity",
    body: "Firms graduating from the programme access preferential pricing to ensure continuity beyond the 12-month window.",
  },
  {
    number: "04",
    icon: Users,
    title: "20 Firms Only",
    body: "Only 20 eligible firms with fewer than 20 active clients can avail this initiative.",
  },
] as const;

const CRITERIA = [
  {
    title: "Be a registered business under DIFC, DFSA, or ADGM",
    body: "Your firm must hold a valid licence or registration with one of the UAE's recognised financial regulators.",
  },
  {
    title: "Have fewer than 20 active clients",
    body: "The programme is designed for smaller independent firms. Up to 20 qualifying firms will be accepted.",
  },
  {
    title: "Be operating in compliance with applicable law and regulation",
    body: "Your firm must be in good standing and conducting business in accordance with all relevant legal and regulatory requirements.",
  },
  {
    title: "Be a regulated, client-facing investment or advisory firm",
    body: "Open exclusively to wealth management, asset management, multi-family office, capital advisory firms, or external asset managers.",
  },
] as const;

const FIRM_TYPE_OPTIONS = [
  "Wealth management firm",
  "Asset management firm",
  "Multi-family office",
  "Capital advisory firm",
  "External asset manager",
] as const;

const SUBMISSION_SUCCESS_DURATION_MS = 5000;

const INPUT_CLASS =
  "w-full bg-transparent text-base text-[hsl(var(--foreground))] outline-none placeholder:text-[hsl(var(--muted-foreground))]/60 focus:placeholder:text-transparent";

const SELECT_CLASS =
  "w-full cursor-pointer bg-transparent text-base text-[hsl(var(--foreground))] outline-none [&>option]:bg-[hsl(var(--card))] [&>option]:text-[hsl(var(--foreground))]";

/** One labelled field on the application form: label over value, closed by a
    hairline, matching the landing page's enquiry form rhythm. When the field
    fails validation the hairline and the label carry the state, and the reason
    is stated underneath — the wrapper keeps the message inside the field's own
    grid cell rather than letting it shift the row. */
function Field({
  label,
  error,
  children,
}: {
  label: React.ReactNode;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <label
        className={`flex flex-col gap-2 border-b pb-3 ${
          error ? "border-[hsl(var(--destructive))]/60" : "border-white/10"
        }`}
      >
        <span
          className={`immersive-label ${error ? "text-[hsl(var(--destructive))]" : ""}`}
        >
          {label}
        </span>
        {children}
      </label>
      {error ? (
        <p role="alert" className="mt-2 text-sm text-[hsl(var(--destructive))]">
          {error}
        </p>
      ) : null}
    </div>
  );
}

type SmeForm = {
  firstName: string;
  lastName: string;
  jobTitle: string;
  workEmail: string;
  firmName: string;
  firmType: string;
  regulator: string;
  activeClients: string;
  yearsInOperation: string;
  challenges: string;
  confirmRegistered: boolean;
  agreeContact: boolean;
};

type SmeErrors = Partial<Record<keyof SmeForm, string>>;

/**
 * Everything the application can check before it costs a round trip.
 *
 * The backend validates the same payload and its 422 response is still handled
 * below; this is the fast, per-field half of that, so an applicant sees which
 * of a dozen fields is wrong next to the field rather than one summary line
 * after a wait. `challenges` is the only optional field on the form.
 */
function validate(values: SmeForm): SmeErrors {
  const errors: SmeErrors = {};

  const required: [keyof SmeForm, string][] = [
    ["firstName", "First name"],
    ["lastName", "Last name"],
    ["jobTitle", "Job title"],
    ["firmName", "Firm name"],
    ["firmType", "Firm type"],
    ["regulator", "Regulator"],
  ];
  for (const [name, label] of required) {
    const error = validateRequired(values[name] as string, label);
    if (error) errors[name] = error;
  }

  const email = validateEmail(values.workEmail, "Work email");
  if (email) errors.workEmail = email;

  const clients = validateNonNegativeNumber(values.activeClients, "Number of active clients");
  if (clients) errors.activeClients = clients;

  const years = validateNonNegativeNumber(values.yearsInOperation, "Years in operation");
  if (years) errors.yearsInOperation = years;

  if (!values.confirmRegistered) {
    errors.confirmRegistered = "Please confirm your firm's registration to apply.";
  }
  if (!values.agreeContact) {
    errors.agreeContact = "Please agree to be contacted so we can process the application.";
  }

  return errors;
}

/**
 * SME Initiative page, styled after the immersive landing page. The form
 * posts the exact same field names to the same same-origin proxy
 * (/api/sme-initiative/apply) as before — only the presentation changed.
 */
export default function SmeInitiativePage() {
  const [formData, setFormData] = useState<SmeForm>({
    firstName: "",
    lastName: "",
    jobTitle: "",
    workEmail: "",
    firmName: "",
    firmType: "",
    regulator: "",
    activeClients: "",
    yearsInOperation: "",
    challenges: "",
    confirmRegistered: false,
    agreeContact: false,
  });
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<SmeErrors>({});

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value, type } = e.target;
    if (type === "checkbox") {
      const { checked } = e.target as HTMLInputElement;
      setFormData((prev) => ({ ...prev, [name]: checked }));
    } else {
      setFormData((prev) => ({ ...prev, [name]: value }));
    }
    // Clear on edit, never re-validate on every keystroke: flagging an email as
    // invalid while it is still being typed is noise, not help.
    setFieldErrors((prev) => clearFieldError(prev, name as keyof SmeForm));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) return;

    const errors = validate(formData);
    setFieldErrors(errors);
    if (Object.keys(errors).length > 0) {
      setSubmitError(null);
      // Focuses the first field that failed, so the applicant lands on the
      // problem instead of hunting for it down a long form.
      scrollToFirstFormError(errors);
      return;
    }

    setSubmitError(null);
    setIsSubmitting(true);

    try {
      // Same-origin proxy route forwards to the public backend endpoint
      // (avoids CORS). formData already has the exact field names the API expects.
      const res = await fetch("/api/sme-initiative/apply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (res.status === 422) {
        const data = await res.json().catch(() => null);
        const firstError =
          data?.errors && typeof data.errors === "object"
            ? (Object.values(data.errors).flat()[0] as string | undefined)
            : undefined;
        setSubmitError(firstError || "Please check your details and try again.");
        return;
      }

      if (!res.ok) {
        setSubmitError("Something went wrong. Please try again.");
        return;
      }

      setIsSubmitted(true);
      setFieldErrors({});
      setTimeout(() => {
        setIsSubmitted(false);
        setFormData({
          firstName: "",
          lastName: "",
          jobTitle: "",
          workEmail: "",
          firmName: "",
          firmType: "",
          regulator: "",
          activeClients: "",
          yearsInOperation: "",
          challenges: "",
          confirmRegistered: false,
          agreeContact: false,
        });
      }, SUBMISSION_SUCCESS_DURATION_MS);
    } catch {
      setSubmitError("Unable to submit right now. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <ImmersivePage>
      <h1 className="sr-only">SME Initiative 2026</h1>

      {/* Hero — a deliberately dark image band, like the homepage's Pricing
          and Security sections: it holds its own contrast regardless of the
          light/dark toggle, since a photo behind light-mode ink would not
          stay legible. */}
      <section className="relative overflow-hidden px-6 pb-16 pt-14 lg:px-12 lg:pb-24 lg:pt-20">
        <Image
          src="/smepic.avif"
          alt=""
          fill
          priority
          sizes="100vw"
          className="object-cover"
          aria-hidden
        />
        <div
          className="absolute inset-0"
          style={{
            background:
              "linear-gradient(160deg, rgba(8,14,11,0.94) 0%, rgba(10,18,14,0.88) 45%, rgba(20,40,26,0.78) 100%)",
          }}
          aria-hidden
        />

        <div className="relative mx-auto w-full max-w-[88rem]">
          <div className="flex items-center justify-between border-b border-white/15 pb-4">
            <span className="immersive-label !text-white/70">SME Initiative</span>
            <span className="immersive-label !text-white/70">[ 2026 ]</span>
          </div>

          <div className="mt-10 grid gap-10 lg:grid-cols-12 lg:gap-16 lg:mt-14">
            <div className="lg:col-span-8">
              <RevealText
                as="h2"
                immediate
                className="immersive-display !text-white"
              >
                UAE wealth & asset management.
              </RevealText>
              <p className="immersive-label immersive-label-accent mt-6">
                Full platform access, complimentary for 12 months
              </p>
            </div>
            <Reveal delay={0.15} className="flex flex-col justify-end gap-7 lg:col-span-4">
              <p className="text-base leading-relaxed text-white/75">
                Oxyfinz is extending institutional-grade reporting and portfolio
                infrastructure to independent advisory firms navigating today&apos;s
                regional market conditions — at no cost.
              </p>
              <a
                href="#apply"
                className="group inline-flex w-fit items-center gap-2 rounded-lg bg-[hsl(var(--primary))] px-6 py-3 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))]"
              >
                Apply for access
                <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
              </a>
            </Reveal>
          </div>
        </div>
      </section>

      {/* About the programme */}
      <section className="immersive-section mt-16 px-6 py-16 lg:mt-24 lg:px-12 lg:py-24">
        <div className="mx-auto w-full max-w-[88rem]">
          <div className="grid gap-8 lg:grid-cols-12 lg:gap-16">
            <div className="lg:col-span-5">
              <span className="immersive-label">About the programme</span>
              <RevealText as="h2" className="immersive-heading mt-4">
                Built for the UAE&apos;s next phase of growth.
              </RevealText>
            </div>
            <Reveal
              stagger={0.08}
              className="flex flex-col gap-5 text-base leading-relaxed text-[hsl(var(--muted-foreground))] lg:col-span-6 lg:col-start-7"
            >
              <p data-reveal>
                The UAE is entering a new era as a global wealth and asset management
                hub. With ADGM reporting 57% growth in assets under management and DIFC
                now home to over 500 asset and wealth management firms, the opportunity
                has never been greater.
              </p>
              <p data-reveal>
                But rapid market expansion is also creating pressure for small and
                independent firms to scale faster, meet rising client expectations, and
                operate with greater efficiency. As the market recovers, firms are
                expected to move quickly and build resilient operations, often without
                the budgets or resources available to larger institutions.
              </p>
              <p data-reveal>
                This initiative is our way of supporting the ecosystem we call home. All
                qualifying firms receive full platform access for 12 months at no cost —
                the same institutional-grade reporting and portfolio infrastructure used
                by larger organisations across the region. No trial conditions. No
                limitations.
              </p>
            </Reveal>
          </div>
        </div>
      </section>

      {/* Key highlights */}
      <section className="immersive-section px-6 py-16 lg:px-12 lg:py-24">
        <div className="mx-auto w-full max-w-[88rem]">
          <div className="immersive-section-head">
            <span className="immersive-label immersive-label-accent">Key highlights</span>
            <span className="immersive-label">What the programme offers</span>
          </div>

          <Reveal stagger={0.08} className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4 lg:gap-5">
            {HIGHLIGHTS.map((item) => {
              const Icon = item.icon;
              return (
                <article key={item.number} data-reveal className="immersive-card p-7">
                  <div className="flex items-center justify-between">
                    <span className="immersive-chip">
                      <Icon className="size-5" aria-hidden />
                    </span>
                    <span className="immersive-label tabular-nums">{item.number}</span>
                  </div>
                  <h3 className="font-heading mt-6 text-lg font-medium leading-snug tracking-tight">
                    {item.title}
                  </h3>
                  <p className="mt-3 text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
                    {item.body}
                  </p>
                </article>
              );
            })}
          </Reveal>
        </div>
      </section>

      {/* Eligibility criteria */}
      <section className="immersive-section px-6 py-16 lg:px-12 lg:py-24">
        <div className="mx-auto w-full max-w-[88rem]">
          <div className="immersive-section-head">
            <span className="immersive-label immersive-label-accent">
              Eligibility criteria
            </span>
            <span className="immersive-label">To qualify, your firm must</span>
          </div>

          <Reveal stagger={0.07} className="mx-auto max-w-4xl">
            {CRITERIA.map((item) => (
              <div
                key={item.title}
                data-reveal
                className="flex items-start gap-5 border-b border-white/10 py-6 first:border-t lg:py-7"
              >
                <CheckCircle2
                  className="mt-0.5 size-5 shrink-0 text-[hsl(var(--primary))]"
                  aria-hidden
                />
                <div>
                  <h3 className="font-heading text-lg font-medium tracking-tight">
                    {item.title}
                  </h3>
                  <p className="mt-2 text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
                    {item.body}
                  </p>
                </div>
              </div>
            ))}
          </Reveal>
        </div>
      </section>

      {/* Registration */}
      <section id="apply" className="immersive-section scroll-mt-24 px-6 py-16 lg:px-12 lg:py-24">
        <div className="mx-auto w-full max-w-[88rem]">
          <div className="immersive-section-head">
            <span className="immersive-label immersive-label-accent">Registration</span>
            <span className="immersive-label">[ Apply ]</span>
          </div>

          <div className="mx-auto max-w-3xl">
            <RevealText as="h2" className="immersive-heading">
              Apply for access.
            </RevealText>
            <Reveal delay={0.1}>
              <p className="mt-5 text-base leading-relaxed text-[hsl(var(--muted-foreground))]">
                Complete the form below and a member of the Oxyfinz team will be in
                touch within two business days to confirm your eligibility and next
                steps.
              </p>
              <a
                href="mailto:hello@oxyfinz.com"
                className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-[hsl(var(--primary))] transition-colors hover:text-[hsl(var(--primary-hover))]"
              >
                <Mail className="size-4" aria-hidden />
                hello@oxyfinz.com
              </a>
            </Reveal>

            <Reveal delay={0.1} className="immersive-card mt-10 p-7 lg:p-10">
              <form onSubmit={handleSubmit} noValidate className="flex flex-col gap-7">
                <div className="grid gap-x-8 gap-y-7 sm:grid-cols-2">
                  <Field label="First name" error={fieldErrors.firstName}>
                    <input
                      type="text"
                      name="firstName"
                      autoComplete="given-name"
                      value={formData.firstName}
                      onChange={handleChange}
                      required
                      className={INPUT_CLASS}
                      placeholder="First name"
                    />
                  </Field>
                  <Field label="Last name" error={fieldErrors.lastName}>
                    <input
                      type="text"
                      name="lastName"
                      autoComplete="family-name"
                      value={formData.lastName}
                      onChange={handleChange}
                      required
                      className={INPUT_CLASS}
                      placeholder="Last name"
                    />
                  </Field>
                  <Field label="Job title" error={fieldErrors.jobTitle}>
                    <input
                      type="text"
                      name="jobTitle"
                      autoComplete="organization-title"
                      value={formData.jobTitle}
                      onChange={handleChange}
                      required
                      className={INPUT_CLASS}
                      placeholder="Job title"
                    />
                  </Field>
                  <Field label="Work email" error={fieldErrors.workEmail}>
                    <input
                      type="email"
                      name="workEmail"
                      autoComplete="email"
                      value={formData.workEmail}
                      onChange={handleChange}
                      required
                      className={INPUT_CLASS}
                      placeholder="you@firm.com"
                    />
                  </Field>
                </div>

                <Field label="Firm name" error={fieldErrors.firmName}>
                  <input
                    type="text"
                    name="firmName"
                    autoComplete="organization"
                    value={formData.firmName}
                    onChange={handleChange}
                    required
                    className={INPUT_CLASS}
                    placeholder="Firm name"
                  />
                </Field>

                <div className="grid gap-x-8 gap-y-7 sm:grid-cols-2">
                  <Field label="Firm type" error={fieldErrors.firmType}>
                    <select
                      name="firmType"
                      autoComplete="off"
                      value={formData.firmType}
                      onChange={handleChange}
                      required
                      className={SELECT_CLASS}
                    >
                      <option value="" disabled>
                        Select firm type
                      </option>
                      {FIRM_TYPE_OPTIONS.map((opt) => (
                        <option key={opt} value={opt}>
                          {opt}
                        </option>
                      ))}
                    </select>
                  </Field>
                  <Field label="Regulator (DIFC / DFSA / ADGM)" error={fieldErrors.regulator}>
                    <select
                      name="regulator"
                      autoComplete="off"
                      value={formData.regulator}
                      onChange={handleChange}
                      required
                      className={SELECT_CLASS}
                    >
                      <option value="" disabled>
                        Select regulator
                      </option>
                      <option value="DIFC">DIFC</option>
                      <option value="DFSA">DFSA</option>
                      <option value="ADGM">ADGM</option>
                    </select>
                  </Field>
                  <Field label="Number of active clients" error={fieldErrors.activeClients}>
                    <input
                      type="number"
                      name="activeClients"
                      autoComplete="off"
                      min={0}
                      value={formData.activeClients}
                      onChange={handleChange}
                      required
                      className={INPUT_CLASS}
                      placeholder="e.g. 12"
                    />
                  </Field>
                  <Field label="Years in operation" error={fieldErrors.yearsInOperation}>
                    <input
                      type="number"
                      name="yearsInOperation"
                      autoComplete="off"
                      min={0}
                      value={formData.yearsInOperation}
                      onChange={handleChange}
                      required
                      className={INPUT_CLASS}
                      placeholder="e.g. 3"
                    />
                  </Field>
                </div>

                <Field
                  label={
                    <>
                      Current operational challenges{" "}
                      <span className="normal-case tracking-normal opacity-70">
                        (optional)
                      </span>
                    </>
                  }
                >
                  <textarea
                    name="challenges"
                    autoComplete="off"
                    value={formData.challenges}
                    onChange={handleChange}
                    rows={4}
                    className={`${INPUT_CLASS} resize-none`}
                    placeholder="Leave blank if not applicable"
                  />
                </Field>

                {/* Declarations */}
                <div className="flex flex-col gap-4 border-t border-white/10 pt-6">
                  <p className="immersive-label immersive-label-accent">Declarations</p>
                  <div>
                    <label className="flex cursor-pointer items-start gap-3 text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
                      <input
                        type="checkbox"
                        name="confirmRegistered"
                        checked={formData.confirmRegistered}
                        onChange={handleChange}
                        required
                        aria-invalid={fieldErrors.confirmRegistered ? true : undefined}
                        aria-describedby={
                          fieldErrors.confirmRegistered ? "confirmRegistered-error" : undefined
                        }
                        className="mt-1 size-4 shrink-0 accent-[hsl(var(--primary))]"
                      />
                      <span>
                        I confirm that my firm is registered with DIFC, DFSA, or ADGM and
                        is operating in compliance with all applicable regulations.
                      </span>
                    </label>
                    {fieldErrors.confirmRegistered ? (
                      <p
                        id="confirmRegistered-error"
                        role="alert"
                        className="mt-2 pl-7 text-sm text-[hsl(var(--destructive))]"
                      >
                        {fieldErrors.confirmRegistered}
                      </p>
                    ) : null}
                  </div>
                  <div>
                    <label className="flex cursor-pointer items-start gap-3 text-sm leading-relaxed text-[hsl(var(--muted-foreground))]">
                      <input
                        type="checkbox"
                        name="agreeContact"
                        checked={formData.agreeContact}
                        onChange={handleChange}
                        required
                        aria-invalid={fieldErrors.agreeContact ? true : undefined}
                        aria-describedby={
                          fieldErrors.agreeContact ? "agreeContact-error" : undefined
                        }
                        className="mt-1 size-4 shrink-0 accent-[hsl(var(--primary))]"
                      />
                      <span>
                        I agree to be contacted by the Oxyfinz team regarding this
                        initiative and understand that my details will be used solely for
                        the purpose of processing this application.
                      </span>
                    </label>
                    {fieldErrors.agreeContact ? (
                      <p
                        id="agreeContact-error"
                        role="alert"
                        className="mt-2 pl-7 text-sm text-[hsl(var(--destructive))]"
                      >
                        {fieldErrors.agreeContact}
                      </p>
                    ) : null}
                  </div>
                </div>

                <div>
                  <button
                    type="submit"
                    disabled={isSubmitted || isSubmitting}
                    className="group inline-flex items-center gap-2 rounded-lg bg-[hsl(var(--primary))] px-6 py-3 text-sm font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))] disabled:opacity-60"
                  >
                    {isSubmitted ? (
                      <>
                        <CheckCircle2 className="size-4" aria-hidden />
                        Application submitted!
                      </>
                    ) : isSubmitting ? (
                      "Submitting…"
                    ) : (
                      <>
                        Submit application
                        <ArrowRight className="size-4 transition-transform group-hover:translate-x-0.5" />
                      </>
                    )}
                  </button>
                  {submitError ? (
                    <p role="alert" className="mt-4 text-sm text-[hsl(var(--destructive))]">
                      {submitError}
                    </p>
                  ) : null}
                </div>
              </form>
            </Reveal>

            {/* Disclaimer */}
            <p className="mt-8 text-xs leading-relaxed text-[hsl(var(--muted-foreground))]/70">
              The UAE Wealth &amp; Asset Management Data Resilience Initiative is offered
              by Oxyfinz at its sole discretion. Eligibility is subject to verification.
              Extension beyond the initial 12-month period is not guaranteed and will be
              assessed based on market conditions and operational factors.
            </p>
          </div>
        </div>
      </section>
    </ImmersivePage>
  );
}
