"use client";

import {
  ArrowRight,
  BadgeIndianRupee,
  BarChart3,
  Check,
  ChevronDown,
  Copy,
  Gift,
  Globe2,
  Link2,
  MousePointerClick,
  Send,
  ShieldCheck,
  Sparkles,
  Users,
} from "lucide-react";
import { FormEvent, useState } from "react";
import { useTenant } from "@/components/tenant-provider";

export default function AffiliateClient() {
  const { tenant, formatMoney } = useTenant();
  const [submitting, setSubmitting] = useState(false);
  const [result, setResult] = useState<{ referralCode: string } | null>(null);
  const [error, setError] = useState("");

  async function apply(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError("");
    const form = new FormData(event.currentTarget);
    try {
      const response = await fetch("/api/affiliates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(Object.fromEntries(form.entries())),
      });
      const data = (await response.json()) as { referralCode?: string; error?: string };
      if (!response.ok || !data.referralCode) throw new Error(data.error || "Application failed");
      setResult({ referralCode: data.referralCode });
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="bg-white text-[#13203c]">
      <section className="relative overflow-hidden bg-[#071f4a] px-5 py-16 text-white sm:py-24">
        <div className="absolute inset-0 opacity-10 [background-image:radial-gradient(#fff_1.2px,transparent_1.2px)] [background-size:24px_24px]" />
        <div className="absolute -right-40 -top-40 h-[520px] w-[520px] rounded-full bg-[#155ee9] opacity-30 blur-3xl" />
        <div className="relative mx-auto grid max-w-7xl items-center gap-14 lg:grid-cols-2">
          <div>
            <span className="inline-flex items-center gap-2 rounded-full border border-[#ffd54a]/30 bg-[#ffd54a]/10 px-3 py-1.5 text-xs font-black uppercase tracking-[0.15em] text-[#ffd54a]"><Sparkles size={14} /> {tenant.brandName} Partner Network</span>
            <h1 className="mt-6 max-w-2xl text-[clamp(2.8rem,6vw,5.4rem)] font-black leading-[0.93] tracking-[-0.055em]">Share great finds.<br /><span className="text-[#ffd54a]">Earn every time.</span></h1>
            <p className="mt-6 max-w-xl text-base leading-7 text-blue-100 sm:text-lg">Help your audience discover products they&apos;ll love. Earn up to 12% commission with simple links, transparent reporting and reliable payouts.</p>
            <div className="mt-8 flex flex-wrap gap-3"><a href="#apply" className="flex items-center gap-2 rounded-xl bg-[#ffd54a] px-6 py-3.5 text-sm font-black text-[#071f4a] shadow-xl">Become a partner <ArrowRight size={17} /></a><a href="#how" className="rounded-xl border border-white/20 px-6 py-3.5 text-sm font-bold hover:bg-white/10">See how it works</a></div>
            <div className="mt-9 flex flex-wrap gap-x-7 gap-y-3 text-xs font-bold text-blue-100"><span className="flex items-center gap-2"><Check size={15} className="text-green-400" /> Free to join</span><span className="flex items-center gap-2"><Check size={15} className="text-green-400" /> 30-day attribution</span><span className="flex items-center gap-2"><Check size={15} className="text-green-400" /> Monthly payouts</span></div>
          </div>
          <div className="relative mx-auto w-full max-w-lg">
            <div className="rounded-[28px] border border-white/10 bg-white p-5 text-[#14203a] shadow-[0_35px_80px_rgba(0,0,0,0.35)] sm:p-7">
              <div className="flex items-center justify-between"><div><p className="text-xs font-bold text-slate-400">Good morning, partner</p><h2 className="mt-1 text-lg font-black">Earnings overview</h2></div><span className="grid h-10 w-10 place-items-center rounded-xl bg-blue-50 text-[#155ee9]"><BarChart3 size={20} /></span></div>
              <div className="mt-6 grid grid-cols-3 gap-2 sm:gap-3">{[[formatMoney(24680), "Commission"], ["1,248", "Orders"], ["5.8%", "Conversion"]].map(([value, label]) => <div key={label} className="rounded-xl bg-[#f4f7fb] p-3"><p className="text-lg font-black sm:text-xl">{value}</p><p className="mt-1 text-[9px] font-bold text-slate-400 sm:text-[10px]">{label}</p></div>)}</div>
              <div className="mt-6"><div className="flex justify-between"><p className="text-xs font-black">Earnings this month</p><p className="text-[10px] font-bold text-green-600">↑ 18.4%</p></div><div className="mt-5 flex h-28 items-end gap-2">{[32, 44, 39, 58, 51, 72, 67, 84, 79, 100, 90, 96].map((height, index) => <span key={index} className="flex-1 rounded-t bg-[#155ee9]" style={{ height: `${height}%`, opacity: 0.28 + index * 0.055 }} />)}</div><div className="mt-2 flex justify-between text-[8px] font-bold text-slate-400"><span>1 MAY</span><span>15 MAY</span><span>31 MAY</span></div></div>
              <div className="mt-6 flex items-center gap-2 rounded-xl border border-dashed border-blue-200 bg-blue-50 p-3"><Link2 size={16} className="text-[#155ee9]" /><span className="flex-1 truncate text-[10px] font-bold text-slate-500">{tenant.customDomain || `${tenant.slug}.marketplace.local`}/deal?ref=MYBRAND</span><Copy size={14} className="text-[#155ee9]" /></div>
            </div>
            <div className="absolute -bottom-5 -left-5 hidden rounded-2xl bg-[#ffd54a] p-4 text-[#071f4a] shadow-xl sm:block"><p className="text-2xl font-black">12%</p><p className="text-[10px] font-black uppercase">up to commission</p></div>
          </div>
        </div>
      </section>

      <section className="border-b border-slate-100 px-5 py-7"><div className="mx-auto flex max-w-6xl flex-wrap items-center justify-center gap-x-12 gap-y-4 text-center"><p className="text-xs font-bold text-slate-400">BUILT FOR</p>{["CREATORS", "PUBLISHERS", "AGENCIES", "CASHBACK", "COMPANIES"].map((brand) => <p key={brand} className="text-sm font-black tracking-wider text-slate-400">{brand}</p>)}</div></section>

      <section id="how" className="px-5 py-16 sm:py-24">
        <div className="mx-auto max-w-7xl">
          <div className="mx-auto max-w-2xl text-center"><p className="text-xs font-black uppercase tracking-[0.18em] text-[#155ee9]">Simple by design</p><h2 className="mt-3 text-3xl font-black tracking-[-0.04em] sm:text-5xl">Three steps to your first earning</h2><p className="mt-4 text-sm leading-6 text-slate-500">We handle checkout, delivery and support. You focus on sharing products your audience will value.</p></div>
          <div className="mt-12 grid gap-5 md:grid-cols-3">
            {[
              [Users, "01", "Join the network", "Apply with your company, channel or website. Our partner team reviews applications quickly."],
              [MousePointerClick, "02", "Create & share links", `Turn any ${tenant.brandName} product or campaign into a trackable link in just a few clicks.`],
              [BadgeIndianRupee, "03", "Earn commission", "See clicks and orders in real time, then receive reliable monthly payouts."],
            ].map(([Icon, number, title, description]) => { const StepIcon = Icon as React.ElementType; return <article key={String(number)} className="relative rounded-3xl border border-slate-200 bg-white p-7 shadow-[0_10px_35px_rgba(24,49,83,0.05)]"><span className="absolute right-6 top-5 text-5xl font-black text-slate-100">{String(number)}</span><span className="grid h-12 w-12 place-items-center rounded-2xl bg-blue-50 text-[#155ee9]"><StepIcon size={23} /></span><h3 className="mt-6 text-xl font-black">{String(title)}</h3><p className="mt-3 text-sm leading-6 text-slate-500">{String(description)}</p></article>; })}
          </div>
        </div>
      </section>

      <section className="bg-[#f4f7fb] px-5 py-16 sm:py-24"><div className="mx-auto grid max-w-7xl gap-12 lg:grid-cols-[0.8fr_1.2fr] lg:items-center"><div><p className="text-xs font-black uppercase tracking-[0.18em] text-[#155ee9]">Partner advantage</p><h2 className="mt-3 text-3xl font-black tracking-[-0.04em] sm:text-5xl">More reasons to grow with {tenant.brandName}.</h2><p className="mt-5 text-sm leading-7 text-slate-500">Access a trusted catalogue and tools that help your business convert more customers.</p></div><div className="grid gap-4 sm:grid-cols-2">{[[Globe2, "Millions of products", "Recommend across electronics, fashion, home, beauty and more."], [BarChart3, "Transparent analytics", "Track clicks, orders, conversion and earnings from one dashboard."], [Gift, "Exclusive campaigns", "Get early access to sales, seasonal offers and higher commissions."], [ShieldCheck, "Reliable attribution", "Benefit from a 30-day cookie window and fraud-protected tracking."]].map(([Icon, title, description]) => { const FeatureIcon = Icon as React.ElementType; return <article key={String(title)} className="rounded-2xl bg-white p-6 shadow-sm"><FeatureIcon size={21} className="text-[#155ee9]" /><h3 className="mt-4 text-base font-black">{String(title)}</h3><p className="mt-2 text-xs leading-5 text-slate-500">{String(description)}</p></article>; })}</div></div></section>

      <section id="apply" className="px-5 py-16 sm:py-24">
        <div className="mx-auto grid max-w-6xl overflow-hidden rounded-[32px] bg-[#071f4a] shadow-[0_30px_70px_rgba(7,31,74,0.18)] lg:grid-cols-[0.8fr_1.2fr]">
          <div className="relative overflow-hidden p-8 text-white sm:p-12"><div className="absolute -bottom-36 -left-28 h-80 w-80 rounded-full bg-[#155ee9] opacity-40" /><div className="relative"><span className="inline-flex rounded-full bg-[#ffd54a] px-3 py-1 text-[10px] font-black uppercase tracking-widest text-[#071f4a]">Applications open</span><h2 className="mt-5 text-3xl font-black tracking-tight sm:text-4xl">Let&apos;s grow together.</h2><p className="mt-4 text-sm leading-6 text-blue-100">Tell us about your company and audience. Our partner team usually responds within 2 business days.</p><div className="mt-8 space-y-4 text-xs font-bold">{["No setup or joining fees", "Dedicated partner support", "Custom campaigns for qualifying companies"].map((item) => <p key={item} className="flex items-center gap-2"><span className="grid h-5 w-5 place-items-center rounded-full bg-green-400 text-[#071f4a]"><Check size={12} /></span>{item}</p>)}</div><p className="mt-10 text-xs text-blue-200">Questions? {tenant.supportEmail}<br />{tenant.phonePrimary}</p></div></div>
          <div className="bg-white p-6 sm:p-10">
            {result ? (
              <div className="flex h-full min-h-[450px] flex-col items-center justify-center text-center"><span className="grid h-20 w-20 place-items-center rounded-full bg-green-100 text-green-600"><Check size={38} strokeWidth={3} /></span><p className="mt-5 text-xs font-black uppercase tracking-[0.15em] text-green-600">Application received</p><h3 className="mt-2 text-2xl font-black">Welcome to the network!</h3><p className="mt-3 max-w-sm text-sm leading-6 text-slate-500">Our team will review your application. Your reserved referral code is:</p><div className="mt-5 rounded-xl border-2 border-dashed border-blue-200 bg-blue-50 px-8 py-4 text-xl font-black tracking-wider text-[#155ee9]">{result.referralCode}</div></div>
            ) : (
              <form onSubmit={apply}>
                <h3 className="text-xl font-black">Partner application</h3><p className="mt-1 text-xs text-slate-500">Fields marked * are required.</p>
                <div className="mt-6 grid gap-4 sm:grid-cols-2"><label className="input-label">Company / channel name *<input required name="companyName" className="checkout-input" placeholder="Acme Media" /></label><label className="input-label">Contact person *<input required name="contactName" className="checkout-input" placeholder="Full name" /></label><label className="input-label">Work email *<input required type="email" name="email" className="checkout-input" placeholder="you@company.com" /></label><label className="input-label">Phone number *<input required type="tel" name="phone" className="checkout-input" placeholder={tenant.country === "Bangladesh" ? "+880 1711 470336" : "+91 98765 43210"} /></label><label className="input-label sm:col-span-2">Website or social channel<input type="url" name="website" className="checkout-input" placeholder="https://yourcompany.com" /></label><label className="input-label sm:col-span-2">Your primary audience *<select required name="audience" className="checkout-input"><option value="">Select audience type</option><option>Shopping & deals</option><option>Technology</option><option>Fashion & beauty</option><option>Home & lifestyle</option><option>Travel</option><option>General audience</option><option>Other business</option></select></label></div>
                {error && <p className="mt-4 rounded-xl bg-red-50 p-3 text-xs font-bold text-red-600">{error}</p>}
                <button disabled={submitting} className="mt-6 flex w-full items-center justify-center gap-2 rounded-xl bg-[#155ee9] px-5 py-3.5 text-sm font-black text-white shadow-lg disabled:opacity-60">{submitting ? "Submitting…" : "Submit application"} <Send size={16} /></button><p className="mt-3 text-center text-[9px] leading-4 text-slate-400">By applying, you agree to the {tenant.brandName} Affiliate Program terms and privacy policy.</p>
              </form>
            )}
          </div>
        </div>
      </section>

      <section className="bg-[#f4f7fb] px-5 py-16"><div className="mx-auto max-w-3xl"><h2 className="text-center text-3xl font-black tracking-tight">Frequently asked questions</h2><div className="mt-8 space-y-3">{[["Who can join the program?", "Content creators, publishers, coupon sites, agencies, communities and registered companies with a relevant audience may apply."], ["How much can I earn?", "Commission varies by category and campaign, with rates up to 12% of qualified order value."], ["When do partners get paid?", "Approved commissions are settled monthly to your verified bank account, subject to the program's minimum payout threshold."], ["Can another company run a co-branded landing page?", "Yes. Qualifying business partners can request custom campaigns and co-branded affiliate landing pages from our partner team."]].map(([question, answer]) => <details key={question} className="group rounded-2xl border border-slate-200 bg-white p-5"><summary className="flex cursor-pointer list-none items-center justify-between text-sm font-black">{question}<ChevronDown size={17} className="transition group-open:rotate-180" /></summary><p className="mt-3 pr-8 text-xs leading-6 text-slate-500">{answer}</p></details>)}</div></div></section>
    </main>
  );
}
