import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  ArrowRight, CheckCircle2, Zap, Link2, BarChart3,
  PenLine, Brain, Mail, Briefcase, Share2, Lock,
  PartyPopper, ChevronRight,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import {
  Form, FormControl, FormField, FormItem, FormLabel, FormMessage,
} from "@/components/ui/form";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import { getPartnerCode } from "@/hooks/use-partner-code";

/* ── Schema ─────────────────────────────────────────── */
const affiliateSchema = z.object({
  firstName: z.string().trim().min(1, "First name is required").max(50),
  lastName: z.string().trim().min(1, "Last name is required").max(50),
  email: z.string().trim().email("Enter a valid email").max(255),
  url: z.string().trim().url("Enter a valid URL").max(255),
  phone: z.string().trim().max(30).optional().or(z.literal("")),
  audience: z.string().min(1, "Please select an option"),
  promotionChannels: z.array(z.string()).min(1, "Select at least one"),
  networkSize: z.string().min(1, "Please select an option"),
  additional: z.string().trim().max(1000).optional().or(z.literal("")),
  agreeTerms: z.literal(true, {
    errorMap: () => ({ message: "You must agree to the terms" }),
  }),
});
type AffiliateFormValues = z.infer<typeof affiliateSchema>;

/* ── Animate on scroll ──────────────────────────────── */
function useAnimateOnScroll() {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => { if (e.isIntersecting) setVisible(true); }, { threshold: 0.15 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return { ref, visible };
}

const AnimatedSection = ({ children, delay = 0, className = "" }: { children: React.ReactNode; delay?: number; className?: string }) => {
  const { ref, visible } = useAnimateOnScroll();
  return (
    <div
      ref={ref}
      className={`transition-all duration-700 ${visible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-6"} ${className}`}
      style={{ transitionDelay: `${delay}ms` }}
    >
      {children}
    </div>
  );
};

/* ── Data ───────────────────────────────────────────── */
const steps = [
  { num: "01", title: "Sign Up", desc: "Fill out the short form below. Approval is fast — usually same day." },
  { num: "02", title: "Share", desc: "Get your unique referral link and share it however you reach your audience — LinkedIn posts, newsletters, YouTube, podcasts, blog content, or direct referrals." },
  { num: "03", title: "Earn", desc: "Every time someone signs up through your link and becomes an active ChatSKU customer, you generate revenue. Track everything in real time." },
];

const whoCards = [
  { icon: PenLine, emoji: "📝", title: "Content Creators", desc: "You write, post, or speak to B2B audiences — manufacturers, distributors, procurement pros. ChatSKU is a natural fit for your followers." },
  { icon: Brain, emoji: "🧠", title: "Industry Consultants", desc: "You advise B2B companies on operations, sales, or digital strategy. ChatSKU is a tool your clients need and you can benefit from recommending." },
  { icon: Mail, emoji: "📧", title: "Newsletter & Community Owners", desc: "You run a list or community of industrial buyers or B2B operators. One mention of ChatSKU to the right audience can generate meaningful returns." },
];

const whatYouGetLeft = [
  "Unique trackable referral link",
  "Real-time referral and earnings dashboard",
  "Ready-made promotional copy and banners",
];
const whatYouGetRight = [
  "Dedicated affiliate support contact",
  "No minimum audience size required",
  "Revenue generated on active customer referrals",
];

const audienceOptions = [
  "B2B manufacturers and distributors",
  "Procurement and sourcing professionals",
  "Industrial business owners",
  "eCommerce and digital strategy community",
  "General business audience",
  "Other",
];

const promotionOptions = [
  "LinkedIn posts",
  "Newsletter or email list",
  "Blog or website",
  "YouTube or podcast",
  "Direct referrals / personal network",
  "Other",
];

const networkSizeOptions = [
  "Under 1,000",
  "1,000 – 5,000",
  "5,000 – 25,000",
  "25,000+",
  "Prefer not to say",
];

/* ── Component ──────────────────────────────────────── */
const Affiliate = () => {
  const [submitted, setSubmitted] = useState(false);
  const formRef = useRef<HTMLDivElement>(null);

  const form = useForm<AffiliateFormValues>({
    resolver: zodResolver(affiliateSchema),
    defaultValues: {
      firstName: "", lastName: "", email: "", url: "", phone: "",
      audience: "", promotionChannels: [], networkSize: "",
      additional: "", agreeTerms: undefined as unknown as true,
    },
  });

  const onSubmit = (data: AffiliateFormValues) => {
    const payload = { ...data, partnerCode: getPartnerCode() };
    console.log("Affiliate signup:", payload);
    setSubmitted(true);
  };

  const scrollToForm = () => {
    formRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const inputClasses = "bg-[#1C2128] border-[#30363D] text-white placeholder:text-[#6E7681] focus-visible:ring-[#00C9A7] focus-visible:ring-2 focus-visible:ring-offset-0";

  return (
    <div className="min-h-screen bg-[#0D1117] text-[#E2E8F0]">
      <Navbar />

      {/* ── Hero ─────────────────────────────────────── */}
      <section className="pt-24 pb-14 relative overflow-hidden">
        <div className="absolute inset-0 opacity-[0.03]" style={{ backgroundImage: "radial-gradient(#00C9A7 1px, transparent 1px)", backgroundSize: "24px 24px" }} />
        <div className="relative max-w-3xl mx-auto px-4 text-center">
          {/* Breadcrumb */}
          <div className="flex items-center justify-center gap-1.5 text-xs text-[#94A3B8] mb-6">
            <Link to="/partners" className="hover:text-[#00C9A7] transition-colors">Partners</Link>
            <ChevronRight className="w-3 h-3" />
            <span className="text-[#00C9A7]">Affiliate Program</span>
          </div>

          <h1 className="text-3xl md:text-5xl font-bold text-white mb-4 leading-tight">
            Share ChatSKU. Earn When Your Referrals Buy.
          </h1>
          <p className="text-base md:text-lg text-[#94A3B8] max-w-2xl mx-auto mb-8 leading-relaxed">
            Join the ChatSKU Affiliate Program — built for B2B content creators, industry consultants, newsletter writers, and LinkedIn voices who reach manufacturing, distribution, and wholesale audiences.
          </p>

          {/* Stat pills */}
          <div className="flex flex-wrap justify-center gap-3 mb-8">
            {[
              { emoji: "⚡", label: "Instant approval" },
              { emoji: "🔗", label: "One unique link" },
              { emoji: "📊", label: "Real-time dashboard" },
            ].map((p) => (
              <span key={p.label} className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#161B22] border border-[#21262D] text-sm text-[#E2E8F0]">
                <span>{p.emoji}</span> {p.label}
              </span>
            ))}
          </div>

          <Button onClick={scrollToForm} className="bg-[#00C9A7] hover:bg-[#00b396] text-[#0D1117] font-semibold px-8 rounded-lg">
            Get My Affiliate Link <ArrowRight className="w-4 h-4 ml-2" />
          </Button>
        </div>
      </section>

      {/* ── How it works ─────────────────────────────── */}
      <section className="py-16 px-4">
        <div className="max-w-5xl mx-auto">
          <AnimatedSection className="text-center mb-10">
            <h2 className="text-2xl md:text-3xl font-bold text-white">How It Works</h2>
          </AnimatedSection>
          <div className="grid md:grid-cols-3 gap-6">
            {steps.map((s, i) => (
              <AnimatedSection key={i} delay={i * 120}>
                <div className="bg-[#161B22] border border-[#21262D] rounded-xl p-6 h-full">
                  <span className="text-2xl font-bold text-[#00C9A7] block mb-2">{s.num}</span>
                  <h3 className="text-lg font-semibold text-white mb-2">{s.title}</h3>
                  <p className="text-sm text-[#94A3B8] leading-relaxed">{s.desc}</p>
                </div>
              </AnimatedSection>
            ))}
          </div>
        </div>
      </section>

      {/* ── Who this is for ──────────────────────────── */}
      <section className="py-16 px-4">
        <div className="max-w-5xl mx-auto">
          <AnimatedSection className="text-center mb-10">
            <h2 className="text-2xl md:text-3xl font-bold text-white">Who This Is For</h2>
          </AnimatedSection>
          <div className="grid md:grid-cols-3 gap-6">
            {whoCards.map((c, i) => (
              <AnimatedSection key={i} delay={i * 120}>
                <div className="bg-[#161B22] border border-[#21262D] rounded-xl p-6 h-full">
                  <span className="text-2xl mb-3 block">{c.emoji}</span>
                  <h3 className="text-lg font-semibold text-white mb-2">{c.title}</h3>
                  <p className="text-sm text-[#94A3B8] leading-relaxed">{c.desc}</p>
                </div>
              </AnimatedSection>
            ))}
          </div>
        </div>
      </section>

      {/* ── What you get ─────────────────────────────── */}
      <section className="py-16 px-4">
        <div className="max-w-3xl mx-auto">
          <AnimatedSection className="text-center mb-10">
            <h2 className="text-2xl md:text-3xl font-bold text-white">What You Get</h2>
          </AnimatedSection>
          <AnimatedSection delay={100}>
            <div className="grid sm:grid-cols-2 gap-x-8 gap-y-3">
              {[...whatYouGetLeft, ...whatYouGetRight].map((f) => (
                <div key={f} className="flex items-start gap-2 text-sm text-[#E2E8F0]">
                  <CheckCircle2 className="w-4 h-4 text-[#00C9A7] mt-0.5 shrink-0" />
                  {f}
                </div>
              ))}
            </div>
          </AnimatedSection>
        </div>
      </section>

      {/* ── Signup form ──────────────────────────────── */}
      <section className="py-16 px-4" ref={formRef}>
        <div className="max-w-2xl mx-auto">
          <AnimatedSection>
            <Card className="bg-[#161B22] border border-[#21262D] rounded-xl">
              <CardContent className="p-8">
                {submitted ? (
                  <div className="text-center py-12">
                    <PartyPopper className="w-12 h-12 text-[#00C9A7] mx-auto mb-4" />
                    <h3 className="text-2xl font-bold text-white mb-3">You're in!</h3>
                    <p className="text-[#94A3B8] max-w-md mx-auto">
                      Check your email for your affiliate link and dashboard access. Welcome to the ChatSKU Partner Program.
                    </p>
                  </div>
                ) : (
                  <>
                    <div className="mb-8">
                      <h2 className="text-xl font-bold text-white mb-1">Join the ChatSKU Affiliate Program</h2>
                      <p className="text-sm text-[#94A3B8]">Quick approval. No minimums. Start sharing the same day.</p>
                    </div>

                    <Form {...form}>
                      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">
                        {/* Name row */}
                        <div className="grid sm:grid-cols-2 gap-4">
                          <FormField control={form.control} name="firstName" render={({ field }) => (
                            <FormItem>
                              <FormLabel className="text-[#E2E8F0] font-medium block">First Name *</FormLabel>
                              <FormControl><Input className={inputClasses} placeholder="Jane" {...field} /></FormControl>
                              <FormMessage className="text-[#F87171]" />
                            </FormItem>
                          )} />
                          <FormField control={form.control} name="lastName" render={({ field }) => (
                            <FormItem>
                              <FormLabel className="text-[#E2E8F0] font-medium block">Last Name *</FormLabel>
                              <FormControl><Input className={inputClasses} placeholder="Smith" {...field} /></FormControl>
                              <FormMessage className="text-[#F87171]" />
                            </FormItem>
                          )} />
                        </div>

                        <FormField control={form.control} name="email" render={({ field }) => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">Email Address *</FormLabel>
                            <FormControl><Input className={inputClasses} placeholder="jane@example.com" {...field} /></FormControl>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <FormField control={form.control} name="url" render={({ field }) => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">Website, Blog, or LinkedIn URL *</FormLabel>
                            <FormControl><Input className={inputClasses} placeholder="Where do you reach your audience?" {...field} /></FormControl>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <FormField control={form.control} name="phone" render={({ field }) => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">Phone Number</FormLabel>
                            <FormControl><Input className={inputClasses} placeholder="+1 (555) 000-0000" {...field} /></FormControl>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <FormField control={form.control} name="audience" render={({ field }) => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">How would you describe your audience? *</FormLabel>
                            <Select onValueChange={field.onChange} defaultValue={field.value}>
                              <FormControl>
                                <SelectTrigger className={inputClasses}>
                                  <SelectValue placeholder="Select one…" />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent className="bg-[#1C2128] border-[#30363D] text-white">
                                {audienceOptions.map((o) => (
                                  <SelectItem key={o} value={o} className="focus:bg-[#00C9A7]/10 focus:text-white">{o}</SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        {/* Promotion channels */}
                        <FormField control={form.control} name="promotionChannels" render={() => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">How do you plan to promote ChatSKU? *</FormLabel>
                            <div className="grid sm:grid-cols-2 gap-2 pt-1">
                              {promotionOptions.map((opt) => (
                                <FormField key={opt} control={form.control} name="promotionChannels" render={({ field }) => (
                                  <FormItem className="flex items-center gap-2">
                                    <FormControl>
                                      <Checkbox
                                        className="border-[#30363D] data-[state=checked]:bg-[#00C9A7] data-[state=checked]:border-[#00C9A7]"
                                        checked={field.value?.includes(opt)}
                                        onCheckedChange={(checked) => {
                                          const v = field.value ?? [];
                                          field.onChange(checked ? [...v, opt] : v.filter((x: string) => x !== opt));
                                        }}
                                      />
                                    </FormControl>
                                    <FormLabel className="text-sm text-[#E2E8F0] font-normal cursor-pointer !mt-0">{opt}</FormLabel>
                                  </FormItem>
                                )} />
                              ))}
                            </div>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <FormField control={form.control} name="networkSize" render={({ field }) => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">Approximate audience or network size *</FormLabel>
                            <Select onValueChange={field.onChange} defaultValue={field.value}>
                              <FormControl>
                                <SelectTrigger className={inputClasses}>
                                  <SelectValue placeholder="Select one…" />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent className="bg-[#1C2128] border-[#30363D] text-white">
                                {networkSizeOptions.map((o) => (
                                  <SelectItem key={o} value={o} className="focus:bg-[#00C9A7]/10 focus:text-white">{o}</SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <FormField control={form.control} name="additional" render={({ field }) => (
                          <FormItem>
                            <FormLabel className="text-[#E2E8F0] font-medium block">Anything else you'd like us to know?</FormLabel>
                            <FormControl><Textarea className={`${inputClasses} min-h-[80px]`} placeholder="Optional" {...field} /></FormControl>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <FormField control={form.control} name="agreeTerms" render={({ field }) => (
                          <FormItem className="flex items-start gap-2">
                            <FormControl>
                              <Checkbox
                                className="border-[#30363D] data-[state=checked]:bg-[#00C9A7] data-[state=checked]:border-[#00C9A7] mt-0.5"
                                checked={field.value === true}
                                onCheckedChange={field.onChange}
                              />
                            </FormControl>
                            <FormLabel className="text-sm text-[#E2E8F0] font-normal !mt-0">
                              I agree to the ChatSKU{" "}
                              <Link to="/terms" className="text-[#00C9A7] hover:underline">Affiliate Program Terms & Conditions</Link>
                            </FormLabel>
                            <FormMessage className="text-[#F87171]" />
                          </FormItem>
                        )} />

                        <Button type="submit" className="w-full bg-[#00C9A7] hover:bg-[#00b396] text-[#0D1117] font-semibold rounded-lg py-3">
                          Get My Affiliate Link <ArrowRight className="w-4 h-4 ml-2" />
                        </Button>

                        <p className="text-xs text-[#94A3B8] text-center flex items-center justify-center gap-1.5">
                          <Lock className="w-3 h-3" /> Your info is never shared or sold. Approval typically same business day.
                        </p>
                      </form>
                    </Form>
                  </>
                )}
              </CardContent>
            </Card>
          </AnimatedSection>
        </div>
      </section>

      <Footer />
    </div>
  );
};

export default Affiliate;
