"use client";

import { useEffect, useRef, useState } from "react";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import {
  CalendarClock,
  CheckCircle2,
  ShieldCheck,
  BadgeCheck,
  Users,
  ArrowRight,
  Mail,
} from "lucide-react";
import Header from "@/sections/Header";
import {
  LANDING_INPUT_FOCUS,
  LANDING_SUBMIT_BTN,
} from "@/sections/landing-constants";

gsap.registerPlugin(ScrollTrigger);

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;

export default function SmeInitiativePage() {
  const heroRef = useRef<HTMLDivElement>(null);
  const aboutRef = useRef<HTMLDivElement>(null);

  const [formData, setFormData] = useState({
    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);

  useEffect(() => {
    const fromTo = (el: unknown, from: gsap.TweenVars, to: gsap.TweenVars) =>
      el && gsap.fromTo(el, from, to);

    const ctx = gsap.context(() => {
      fromTo(heroRef.current, { y: 28, opacity: 0 }, {
        y: 0,
        opacity: 1,
        duration: 0.7,
        ease: "power2.out",
      });
      fromTo(aboutRef.current, { y: 28, opacity: 0 }, {
        y: 0,
        opacity: 1,
        duration: 0.65,
        ease: "power2.out",
        scrollTrigger: { trigger: aboutRef.current, start: "top 85%" },
      });
      gsap.utils.toArray<HTMLElement>(".sme-reveal").forEach((el) => {
        gsap.fromTo(el, { y: 24, opacity: 0 }, {
          y: 0,
          opacity: 1,
          duration: 0.55,
          ease: "power2.out",
          scrollTrigger: { trigger: el, start: "top 90%" },
        });
      });
    });
    return () => ctx.revert();
  }, []);

  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 }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isSubmitting) 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);
      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 (
    <div className="min-h-screen bg-white">
      <Header />
      <h1 className="sr-only">SME Initiative 2026</h1>

      <main className="site-main">
        <div className="h-16 lg:h-20" aria-hidden="true" />

        {/* Hero */}
        <section
          className="relative py-16 lg:py-24 overflow-hidden bg-[#0a1410] bg-cover bg-center"
          style={{ backgroundImage: "url('/smepic.avif')" }}
        >
          {/* Readability overlay */}
          <div
            className="absolute inset-0"
            style={{
              background:
                "linear-gradient(160deg, rgba(8, 20, 14, 0.92) 0%, rgba(10, 26, 17, 0.82) 45%, rgba(66, 139, 77, 0.55) 100%)",
            }}
            aria-hidden="true"
          />
          <div className="landing-container max-w-5xl relative z-10">
            <div ref={heroRef} className="text-center">
              <h1
                className="font-heading font-bold text-3xl sm:text-4xl lg:text-5xl xl:text-[3.25rem] leading-[1.12] tracking-tight mb-4"
                style={{ color: "#ffffff" }}
              >
                UAE Wealth &amp; Asset Management — SME Initiative 2026
              </h1>
              <p className="text-sm sm:text-base font-medium uppercase tracking-[0.18em] text-[#8fd49b] mb-6">
                Full Platform Access, Complimentary for 12 Months
              </p>
              <p className="text-white/80 text-base lg:text-lg leading-relaxed max-w-2xl mx-auto mb-8">
                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="inline-flex items-center gap-2 px-7 py-3.5 rounded-2xl bg-[#428b4d] text-white font-semibold text-base shadow-xl shadow-black/30 hover:bg-[#3a7a42] hover:-translate-y-0.5 transition-all duration-300"
              >
                Apply for access
                <ArrowRight className="h-5 w-5" aria-hidden />
              </a>
            </div>
          </div>
        </section>

        {/* About the programme */}
        <section className="relative py-14 lg:py-20 bg-white overflow-hidden">
          <div
            className="absolute left-0 top-0 bottom-0 w-1 sm:w-1.5 rounded-r-full bg-gradient-to-b from-[#428b4d]/20 via-[#428b4d]/40 to-[#428b4d]/20 hidden sm:block"
            aria-hidden="true"
          />
          <div className="landing-container max-w-4xl relative">
            <div ref={aboutRef} className="pl-0 sm:pl-6">
              <p className="text-xs font-semibold uppercase tracking-[0.25em] text-[#428b4d] mb-5">
                About the Programme
              </p>
              <h2 className="font-heading font-bold text-3xl sm:text-4xl lg:text-[2.75rem] text-[#0a0a0a] leading-[1.15] tracking-tight mb-8">
                Built for the UAE's Next Phase of Growth
              </h2>
              <div className="space-y-5 text-slate-600 text-lg leading-relaxed max-w-3xl">
                <p>
                  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>
                  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>
                  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>
              </div>
            </div>
          </div>
        </section>

        {/* Key Highlights */}
        <section className="py-12 lg:py-16 bg-[#fafbfc] border-y border-slate-200/80">
          <div className="landing-container max-w-6xl">
            <p className="text-xs font-semibold uppercase tracking-[0.25em] text-[#428b4d] mb-3 text-center">
              Key Highlights
            </p>
            <h2 className="font-heading font-bold text-2xl sm:text-3xl lg:text-4xl text-[#0a0a0a] text-center mb-12 tracking-tight">
              What the programme offers
            </h2>
            <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {HIGHLIGHTS.map((item) => {
                const Icon = item.icon;
                return (
                  <div
                    key={item.number}
                    className="sme-reveal relative rounded-2xl border border-slate-200/90 bg-white p-7 lg:p-8 shadow-sm hover:shadow-lg hover:border-[#428b4d]/20 transition-all duration-300"
                  >
                    <span className="absolute top-6 right-7 font-heading font-bold text-4xl text-[#428b4d]/10">
                      {item.number}
                    </span>
                    <div className="mb-5 w-12 h-12 rounded-xl bg-[#428b4d]/10 flex items-center justify-center">
                      <Icon className="w-6 h-6 text-[#428b4d]" aria-hidden />
                    </div>
                    <h3 className="font-heading font-bold text-xl text-[#0a0a0a] mb-3">
                      {item.title}
                    </h3>
                    <p className="text-slate-600 leading-relaxed">{item.body}</p>
                  </div>
                );
              })}
            </div>
          </div>
        </section>

        {/* Eligibility criteria */}
        <section className="py-12 lg:py-16 bg-[#fafbfc] border-y border-slate-200/80">
          <div className="landing-container max-w-4xl">
            <p className="text-xs font-semibold uppercase tracking-[0.25em] text-[#428b4d] mb-3 text-center">
              Eligibility Criteria
            </p>
            <h2 className="font-heading font-bold text-2xl sm:text-3xl lg:text-4xl text-[#0a0a0a] text-center mb-12 tracking-tight">
              To Qualify, Your Firm Must
            </h2>
            <div className="space-y-5">
              {CRITERIA.map((item) => (
                <div
                  key={item.title}
                  className="sme-reveal flex items-start gap-4 rounded-2xl border border-slate-200/90 bg-white p-6 lg:p-7 shadow-sm"
                >
                  <CheckCircle2 className="w-6 h-6 text-[#428b4d] flex-shrink-0 mt-0.5" aria-hidden />
                  <div>
                    <h3 className="font-heading font-semibold text-lg text-[#0a0a0a] mb-2">
                      {item.title}
                    </h3>
                    <p className="text-slate-600 leading-relaxed">{item.body}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* Registration */}
        <section id="apply" className="py-14 lg:py-20 bg-white scroll-mt-20">
          <div className="landing-container max-w-3xl">
            <div className="text-center mb-12">
              <p className="text-xs font-semibold uppercase tracking-[0.25em] text-[#428b4d] mb-3">
                Registration
              </p>
              <h2 className="font-heading font-bold text-2xl sm:text-3xl lg:text-4xl text-[#0a0a0a] mb-5 tracking-tight">
                Apply for Access
              </h2>
              <p className="text-slate-600 text-lg leading-relaxed max-w-2xl mx-auto">
                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="inline-flex items-center gap-2 mt-5 text-[#428b4d] font-semibold hover:underline"
              >
                <Mail className="w-4 h-4" aria-hidden />
                hello@oxyfinz.com
              </a>
            </div>

            <form
              onSubmit={handleSubmit}
              className="rounded-3xl border border-slate-200/90 bg-[#fafbfc] p-6 sm:p-8 lg:p-10 shadow-lg shadow-slate-200/50 space-y-5"
            >
              <div className="grid sm:grid-cols-2 gap-5">
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">First Name</label>
                  <input
                    type="text"
                    name="firstName"
                    value={formData.firstName}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                    placeholder="First name"
                  />
                </div>
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">Last Name</label>
                  <input
                    type="text"
                    name="lastName"
                    value={formData.lastName}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                    placeholder="Last name"
                  />
                </div>
              </div>

              <div className="grid sm:grid-cols-2 gap-5">
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">Job Title</label>
                  <input
                    type="text"
                    name="jobTitle"
                    value={formData.jobTitle}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                    placeholder="Job title"
                  />
                </div>
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">Work Email</label>
                  <input
                    type="email"
                    name="workEmail"
                    value={formData.workEmail}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                    placeholder="you@firm.com"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm text-slate-600 mb-2 font-medium">Firm Name</label>
                <input
                  type="text"
                  name="firmName"
                  value={formData.firmName}
                  onChange={handleChange}
                  required
                  className={LANDING_INPUT_FOCUS}
                  placeholder="Firm name"
                />
              </div>

              <div className="grid sm:grid-cols-2 gap-5">
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">Firm Type</label>
                  <select
                    name="firmType"
                    value={formData.firmType}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                  >
                    <option value="" disabled>
                      Select firm type
                    </option>
                    {FIRM_TYPE_OPTIONS.map((opt) => (
                      <option key={opt} value={opt}>
                        {opt}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">
                    Regulator (DIFC / DFSA / ADGM)
                  </label>
                  <select
                    name="regulator"
                    value={formData.regulator}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                  >
                    <option value="" disabled>
                      Select regulator
                    </option>
                    <option value="DIFC">DIFC</option>
                    <option value="DFSA">DFSA</option>
                    <option value="ADGM">ADGM</option>
                  </select>
                </div>
              </div>

              <div className="grid sm:grid-cols-2 gap-5">
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">
                    Number of Active Clients
                  </label>
                  <input
                    type="number"
                    name="activeClients"
                    min={0}
                    value={formData.activeClients}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                    placeholder="e.g. 12"
                  />
                </div>
                <div>
                  <label className="block text-sm text-slate-600 mb-2 font-medium">
                    Years in Operation
                  </label>
                  <input
                    type="number"
                    name="yearsInOperation"
                    min={0}
                    value={formData.yearsInOperation}
                    onChange={handleChange}
                    required
                    className={LANDING_INPUT_FOCUS}
                    placeholder="e.g. 3"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm text-slate-600 mb-2 font-medium">
                  Current Operational Challenges{" "}
                  <span className="text-slate-400 font-normal">(optional)</span>
                </label>
                <textarea
                  name="challenges"
                  value={formData.challenges}
                  onChange={handleChange}
                  rows={4}
                  className={LANDING_INPUT_FOCUS}
                  placeholder="Leave blank if not applicable"
                />
              </div>

              {/* Declarations */}
              <div className="space-y-3 pt-2">
                <p className="text-sm font-semibold text-[#0a0a0a]">Declarations</p>
                <label className="flex items-start gap-3 text-sm text-slate-600 leading-relaxed cursor-pointer">
                  <input
                    type="checkbox"
                    name="confirmRegistered"
                    checked={formData.confirmRegistered}
                    onChange={handleChange}
                    required
                    className="mt-1 w-4 h-4 rounded border-slate-300 text-[#428b4d] focus:ring-[#428b4d]/30"
                  />
                  <span>
                    I confirm that my firm is registered with DIFC, DFSA, or ADGM and is
                    operating in compliance with all applicable regulations.
                  </span>
                </label>
                <label className="flex items-start gap-3 text-sm text-slate-600 leading-relaxed cursor-pointer">
                  <input
                    type="checkbox"
                    name="agreeContact"
                    checked={formData.agreeContact}
                    onChange={handleChange}
                    required
                    className="mt-1 w-4 h-4 rounded border-slate-300 text-[#428b4d] focus:ring-[#428b4d]/30"
                  />
                  <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>
              </div>

              <button
                type="submit"
                disabled={isSubmitted || isSubmitting}
                className={LANDING_SUBMIT_BTN}
              >
                {isSubmitted ? (
                  <>
                    <span className="relative flex h-5 w-5 items-center justify-center">
                      <span className="absolute inline-flex h-full w-full rounded-full bg-white/40 animate-ping" />
                      <CheckCircle2 size={18} className="relative" />
                    </span>
                    <span className="animate-pulse">Application submitted!</span>
                  </>
                ) : isSubmitting ? (
                  <>Submitting…</>
                ) : (
                  <>
                    Submit application
                    <ArrowRight size={16} />
                  </>
                )}
              </button>

              {submitError && (
                <p className="text-sm text-red-500 mt-3 text-center">{submitError}</p>
              )}
            </form>

            {/* Disclaimer */}
            <p className="text-xs text-slate-400 leading-relaxed mt-8 max-w-3xl mx-auto text-center">
              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>
        </section>
      </main>
    </div>
  );
}
