import { ArrowRight, Shield, BookOpen, Award } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Link } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import { useQuery } from '@tanstack/react-query';

type HeroData = {
  stats: { courses: number; delegates: number; pass_rate: number };
  upcoming_courses: Array<{ title: string; slug: string; days: number; price_cents: number; start_date?: string }>;
};

const trustBadges = [
  { icon: Shield, label: 'CITB Approved' },
  { icon: BookOpen, label: 'NRSWA Accredited' },
  { icon: Award, label: 'City & Guilds' },
];

const AnimatedCounter = ({ target, suffix }: { target: number; suffix: string }) => {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLDivElement>(null);
  const hasAnimated = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    hasAnimated.current = false;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !hasAnimated.current) {
          hasAnimated.current = true;
          const duration = 1500;
          const start = performance.now();
          const animate = (now: number) => {
            const progress = Math.min((now - start) / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3);
            setCount(Math.round(eased * target));
            if (progress < 1) requestAnimationFrame(animate);
          };
          requestAnimationFrame(animate);
        }
      },
      { threshold: 0.5 },
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, [target]);

  return (
    <div ref={ref} className="text-4xl font-extrabold text-stat">
      {count}{suffix}
    </div>
  );
};

const HeroSection = () => {
  const { data: hero } = useQuery<HeroData>({
    queryKey: ['marketplace-hero'],
    queryFn: async () => {
      const res = await fetch('/api/marketplace/hero');
      if (!res.ok) throw new Error('hero fetch failed');
      return res.json();
    },
  });

  const stats = [
    { value: hero?.stats?.courses ?? 0, suffix: '+', label: 'Classroom Courses' },
    { value: hero?.stats?.delegates ?? 0, suffix: '+', label: 'Certified Professionals' },
    { value: hero?.stats?.pass_rate ?? 98, suffix: '%', label: 'Pass Rate' },
  ];

  const upcoming = hero?.upcoming_courses ?? [];

  const fmtDays = (d: number) => `${d} ${d === 1 ? 'day' : 'days'}`;
  const fmtPrice = (c: number) =>
    `£${(c / 100).toLocaleString('en-GB', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  const fmtDate = (iso: string) => {
    const [y, m, d] = iso.slice(0, 10).split('-').map(Number);
    if (!y || !m || !d) return null;
    return new Date(y, m - 1, d).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
  };

  return (
    <section className="relative min-h-screen flex items-center overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-br from-background via-background to-primary/5" />

      <div className="container mx-auto px-4 relative z-10 pt-20 md:pt-24">
        <div className="grid lg:grid-cols-2 gap-8 lg:gap-12 items-center">
          <div>
            <div className="inline-flex items-center gap-2 rounded-full border border-primary/30 bg-primary/10 px-3 py-1 sm:px-4 sm:py-1.5 mb-4 sm:mb-6">
              <span className="w-2 h-2 rounded-full bg-primary animate-pulse" />
              <span className="text-xs sm:text-sm text-primary font-medium">Industry-Accredited Training</span>
            </div>

            <h1 className="text-3xl sm:text-5xl md:text-7xl font-extrabold text-foreground mb-3 sm:mb-4 leading-tight">
              Utility Training Centre
            </h1>

            <p className="text-base sm:text-lg text-muted-foreground mb-6 sm:mb-8 max-w-lg">
              From theory to the field — accredited training courses for utility and street works professionals across the UK.
            </p>

            <div className="flex flex-wrap gap-3 sm:gap-4 mb-8 sm:mb-10">
              <Link href="/courses">
                <Button size="lg" className="px-8 py-6 text-base">
                  Browse Courses <ArrowRight className="w-4 h-4 ml-1" />
                </Button>
              </Link>
              <Link href="/contact">
                <Button variant="outline" size="lg" className="px-8 py-6 text-base">
                  Contact Us
                </Button>
              </Link>
            </div>

            <div className="grid grid-cols-2 sm:flex sm:gap-12 gap-x-8 gap-y-4 mb-6 sm:mb-8">
              {stats.map((stat) => (
                <div key={stat.label}>
                  <AnimatedCounter target={stat.value} suffix={stat.suffix} />
                  <div className="text-xs sm:text-sm text-muted-foreground mt-1">{stat.label}</div>
                </div>
              ))}
            </div>

            <div className="flex gap-4 sm:gap-6 flex-wrap">
              {trustBadges.map((badge) => (
                <div key={badge.label} className="flex items-center gap-1.5 sm:gap-2 text-xs text-muted-foreground">
                  <badge.icon className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
                  <span>{badge.label}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="hidden lg:block">
            <div className="relative">
              <div className="bg-card border border-border rounded-2xl p-8 shadow-xl">
                <div className="flex items-center gap-3 mb-6">
                  <div className="w-10 h-10 rounded-lg bg-primary flex items-center justify-center">
                    <BookOpen className="w-5 h-5 text-primary-foreground" />
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-foreground">Next Available Courses</p>
                    <p className="text-xs text-muted-foreground">Book your place today</p>
                  </div>
                </div>
                <div className="space-y-4">
                  {upcoming.length > 0 ? (
                    upcoming.map((course) => (
                      <Link
                        key={course.slug}
                        href={`/course/${course.slug}`}
                        className="flex items-center justify-between p-3 rounded-lg bg-background border border-border hover:border-primary/40 transition-colors"
                      >
                        <div>
                          <p className="text-sm font-medium text-foreground">{course.title}</p>
                          <p className="text-xs text-muted-foreground">{fmtDays(course.days)}</p>
                          {course.start_date && fmtDate(course.start_date) && (
                            <p className="text-xs text-muted-foreground">
                              Date currently booking up: <span className="text-foreground font-medium">{fmtDate(course.start_date)}</span>
                            </p>
                          )}
                        </div>
                        <span className="text-sm font-bold text-primary">{fmtPrice(course.price_cents)}</span>
                      </Link>
                    ))
                  ) : (
                    <div className="p-3 rounded-lg bg-background border border-border text-center text-xs text-muted-foreground">
                      No courses available right now — check back soon.
                    </div>
                  )}
                </div>
                {upcoming.length > 0 && (
                  <p className="text-xs text-muted-foreground text-center mt-6">
                    Above are upcoming dates with open seats. Looking for something else?
                  </p>
                )}
                <Link href="/courses">
                  <Button className={`w-full ${upcoming.length > 0 ? 'mt-3' : 'mt-6'}`}>
                    Explore all options <ArrowRight className="w-4 h-4 ml-1" />
                  </Button>
                </Link>
              </div>

              <div className="absolute -top-4 -right-4 bg-primary text-primary-foreground rounded-full px-4 py-2 text-sm font-bold shadow-lg">
                {hero?.stats?.pass_rate ?? 98}% Pass Rate
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default HeroSection;
