'use client'

import { Suspense, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'
import {
  ArrowRight,
  Award,
  BookOpen,
  CheckCircle2,
  Clock,
  Globe,
  GraduationCap,
  Monitor,
  Sparkles,
  Timer,
  Users,
  Video,
} from 'lucide-react'
import { PageHero } from '@/components/page-hero'
import { DataStates } from '@/components/api/data-states'
import { InfiniteScrollSentinel } from '@/components/api/infinite-scroll-sentinel'
import { useFetchData } from '@/hooks/api'
import type { OnlineCourse } from '@/lib/api/entities'
import type { CategoryFilter } from '@/lib/courses'
import { cn } from '@/lib/utils'

const benefits = [
  {
    icon: Globe,
    title: 'International Peer Networking',
    text: 'Connect and collaborate with professionals from across Asia, the Middle East, Africa, and beyond.',
  },
  {
    icon: BookOpen,
    title: 'Practical Case Studies',
    text: 'Work through real-world scenarios and industry case studies directly applicable to your role.',
  },
  {
    icon: Award,
    title: 'Digital Certificate',
    text: 'Receive a globally recognised digital certificate of completion upon finishing your programme.',
  },
  {
    icon: GraduationCap,
    title: 'Lifetime Learning Resources',
    text: 'Retain permanent access to all course materials, recordings, and toolkits after the programme ends.',
  },
  {
    icon: Users,
    title: 'Small Executive Cohorts',
    text: 'Intimate cohorts of 15–25 participants ensure personalised attention and meaningful peer exchange.',
  },
  {
    icon: Timer,
    title: 'Flexible Global Time Zones',
    text: 'Sessions scheduled to accommodate participants across Asia-Pacific, MENA, and European time zones.',
  },
  {
    icon: Video,
    title: 'Live Instructor-Led Learning',
    text: 'Every session is delivered live by an expert facilitator — not pre-recorded — with real-time Q&A.',
  },
  {
    icon: Sparkles,
    title: 'Interactive Breakout Rooms',
    text: 'Collaborate in small groups through structured breakout exercises, peer discussions, and team challenges.',
  },
]

const LEVEL_COLOURS: Record<string, string> = {
  Advanced: 'border-primary/25 bg-primary/8 text-primary',
  Intermediate: 'border-accent/30 bg-accent/10 text-accent',
  Foundation: 'border-border bg-[oklch(0.975_0.01_343)] text-muted-foreground',
}

const PLATFORM_TAGS = ['Zoom', 'Google Meet', 'Live Q&A', 'Breakout Rooms', 'Screen Sharing'] as const

function LiveOnlineCoursesContent() {
  const [selectedCategory, setSelectedCategory] = useState('All')

  const { items, isLoading, isError, isEmpty, error, refetch, loadMore, hasMore, isLoadingMore } =
    useFetchData<OnlineCourse>({
      endpoint: 'online-courses',
      infinite: true,
      initialPageSize: 12,
    })

  const onlineCourses = items ?? []

  const categories = useMemo<CategoryFilter[]>(() => {
    const unique = Array.from(new Set(onlineCourses.map((c) => c.category)))
    return [
      { name: 'All', slug: null, count: onlineCourses.length },
      ...unique.map((name) => ({
        name,
        slug: null,
        count: onlineCourses.filter((c) => c.category === name).length,
      })),
    ]
  }, [onlineCourses])

  const filteredCourses = useMemo(() => {
    if (selectedCategory === 'All') return onlineCourses
    return onlineCourses.filter((c) => c.category === selectedCategory)
  }, [onlineCourses, selectedCategory])

  return (
    <>
      <section className="border-b border-border/70 bg-white">
        <div className="container-wide py-14 sm:py-16 md:py-20">
          <div className="grid items-center gap-10 lg:grid-cols-2 lg:gap-14">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                Live Virtual Sessions
              </p>
              <span className="mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
              <h2 className="mt-5 font-heading text-3xl leading-tight text-foreground sm:text-4xl">
                Real instructors. Real interaction. From anywhere in the world.
              </h2>
              <p className="mt-4 text-base leading-7 text-muted-foreground sm:text-lg sm:leading-8">
                Our live online sessions are delivered via Zoom and Google Meet — not pre-recorded videos.
                Join with or without headphones, interact with your facilitator in real time, and collaborate
                with peers from across the globe in breakout rooms and live exercises.
              </p>
              <div className="mt-6 flex flex-wrap gap-2">
                {PLATFORM_TAGS.map((tag) => (
                  <span
                    key={tag}
                    className="inline-flex items-center gap-1.5 border border-border bg-[oklch(0.985_0.008_343)] px-3 py-1.5 text-xs font-semibold text-foreground"
                  >
                    <Monitor className="h-3 w-3 text-primary" />
                    {tag}
                  </span>
                ))}
              </div>
            </div>

            <div className="border border-border/80 bg-[oklch(0.22_0.07_343)] text-white shadow-[0_20px_50px_rgba(15,23,42,0.18)]">
              <div className="flex items-center gap-2 border-b border-white/10 px-4 py-3">
                <span className="h-2.5 w-2.5 bg-red-400" />
                <span className="h-2.5 w-2.5 bg-yellow-400" />
                <span className="h-2.5 w-2.5 bg-green-400" />
                <span className="ml-2 flex-1 bg-white/10 px-3 py-1 text-xs text-white/55">
                  zoom.us / meet.google.com
                </span>
                <span className="bg-accent/20 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.12em] text-accent">
                  Live
                </span>
              </div>
              <div className="grid grid-cols-3 gap-2 p-3">
                {[
                  { initials: 'FA', label: 'Facilitator', speaking: true },
                  { initials: 'MK', label: 'Bangkok', speaking: false },
                  { initials: 'SR', label: 'Dubai', speaking: false },
                  { initials: 'JL', label: 'Singapore', speaking: false },
                  { initials: 'AN', label: 'Nairobi', speaking: false },
                  { initials: 'PW', label: 'London', speaking: false },
                ].map((p) => (
                  <div
                    key={p.initials}
                    className={cn(
                      'relative flex flex-col items-center justify-center gap-1 py-4',
                      p.speaking ? 'bg-primary/30 ring-1 ring-accent' : 'bg-white/5',
                    )}
                  >
                    <div
                      className={cn(
                        'flex h-10 w-10 items-center justify-center text-sm font-bold text-white',
                        p.speaking ? 'bg-primary' : 'bg-white/15',
                      )}
                    >
                      {p.initials}
                    </div>
                    <span className="text-[10px] text-white/55">{p.label}</span>
                  </div>
                ))}
              </div>
              <div className="flex items-center justify-between border-t border-white/10 px-4 py-3">
                <span className="text-xs text-white/55">6 participants connected</span>
                <span className="text-xs font-semibold text-accent">Strategic Leadership Masterclass</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="border-b border-border/70 bg-[oklch(0.975_0.01_343)] py-16 sm:py-20 md:py-24">
        <div className="container-wide">
          <div className="mx-auto mb-10 max-w-3xl text-center md:mb-12">
            <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">Why Live Online</p>
            <span className="mx-auto mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
            <h2 className="mt-4 font-heading text-3xl text-foreground sm:text-4xl">
              Everything you get with every programme
            </h2>
          </div>
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            {benefits.map(({ icon: Icon, title, text }, index) => (
              <article
                key={title}
                className="border border-border/80 bg-white p-6 transition duration-300 hover:border-secondary/40 hover:shadow-[0_16px_40px_rgba(15,23,42,0.06)]"
              >
                <div className="flex items-center justify-between">
                  <span className="flex h-11 w-11 items-center justify-center bg-primary/8 text-primary">
                    <Icon className="h-5 w-5" />
                  </span>
                  <span className="font-mono text-xs text-muted-foreground">
                    {String(index + 1).padStart(2, '0')}
                  </span>
                </div>
                <h3 className="mt-5 text-sm font-bold text-foreground">{title}</h3>
                <p className="mt-2 text-sm leading-6 text-muted-foreground">{text}</p>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="sticky top-[4.25rem] z-30 border-b border-border/70 bg-white/95 backdrop-blur-md">
        <div className="container-wide py-4">
          <div className="mb-3 flex items-center justify-between gap-3">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-secondary">Catalogue</p>
              <p className="mt-0.5 text-sm text-muted-foreground">
                {selectedCategory === 'All' ? 'All live programmes' : selectedCategory}
                {' · '}
                <span className="font-semibold text-foreground">{filteredCourses.length}</span> results
              </p>
            </div>
          </div>
          <nav
            aria-label="Online course categories"
            className="flex gap-2 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
          >
            {categories.map((category) => {
              const active = selectedCategory === category.name
              return (
                <button
                  key={category.name}
                  type="button"
                  onClick={() => setSelectedCategory(category.name)}
                  className={cn(
                    'inline-flex h-10 shrink-0 items-center gap-2 border px-4 text-sm font-semibold transition',
                    active
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-border bg-[oklch(0.985_0.008_343)] text-foreground hover:border-secondary hover:bg-white',
                  )}
                  aria-current={active ? 'true' : undefined}
                >
                  {category.name}
                  <span className={cn('text-xs tabular-nums', active ? 'text-primary-foreground/80' : 'text-muted-foreground')}>
                    {category.count}
                  </span>
                </button>
              )
            })}
          </nav>
        </div>
      </section>

      <section className="border-b border-border/70 bg-white py-12 sm:py-16 md:py-20">
        <div className="container-wide">
          <DataStates
            isLoading={isLoading}
            isError={isError}
            isEmpty={isEmpty}
            error={error}
            loadingMessage="Loading online courses…"
            emptyMessage="No live online courses scheduled yet. Check back soon or contact us to discuss a custom session."
            onRetry={refetch}
            skeleton={
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3" aria-busy="true">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div key={i} className="min-h-[360px] animate-pulse bg-muted" />
                ))}
              </div>
            }
          >
            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
              {filteredCourses.map((course) => (
                <article
                  key={course.id}
                  className="flex flex-col border border-border/80 bg-[oklch(0.985_0.008_343)] transition duration-300 hover:border-secondary/40 hover:bg-white hover:shadow-[0_16px_40px_rgba(15,23,42,0.06)]"
                >
                  <div className="flex flex-1 flex-col p-6 sm:p-7">
                    <div className="mb-4 flex flex-wrap items-center gap-2">
                      <span className="border border-border bg-white px-3 py-1 text-xs font-semibold text-foreground">
                        {course.category}
                      </span>
                      <span
                        className={cn(
                          'border px-3 py-1 text-xs font-semibold',
                          LEVEL_COLOURS[course.level] ?? LEVEL_COLOURS.Foundation,
                        )}
                      >
                        {course.level}
                      </span>
                    </div>

                    <h3 className="font-heading text-xl leading-snug text-foreground">{course.title}</h3>
                    <p className="mt-2 text-sm leading-6 text-muted-foreground">{course.description}</p>

                    <div className="mt-5 space-y-2 text-sm text-muted-foreground">
                      <div className="flex items-center gap-2">
                        <Clock className="h-4 w-4 shrink-0 text-primary" />
                        {course.duration}
                      </div>
                      <div className="flex items-center gap-2">
                        <Users className="h-4 w-4 shrink-0 text-primary" />
                        Max {course.participants} participants
                      </div>
                      <div className="flex items-center gap-2">
                        <Globe className="h-4 w-4 shrink-0 text-primary" />
                        {course.timezone}
                      </div>
                    </div>

                    {course.features.length > 0 ? (
                      <ul className="mt-5 space-y-1.5 border-t border-border/70 pt-5">
                        {course.features.map((f) => (
                          <li key={f} className="flex items-start gap-2 text-xs text-muted-foreground">
                            <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
                            {f}
                          </li>
                        ))}
                      </ul>
                    ) : null}
                  </div>

                  <div className="border-t border-border/70 bg-white px-6 py-5 sm:px-7">
                    <div className="mb-4 flex items-center justify-between gap-3">
                      <span className="font-heading text-2xl text-primary">{course.price}</span>
                      <span className="text-xs text-muted-foreground">Starts {course.startDate}</span>
                    </div>
                    <Link
                      href={`/contact?subject=course-inquiry&course=${encodeURIComponent(course.title)}`}
                      className="inline-flex h-11 w-full items-center justify-center gap-2 bg-primary text-sm font-semibold text-primary-foreground transition hover:bg-primary/90"
                    >
                      Register Now
                      <ArrowRight className="h-4 w-4" />
                    </Link>
                  </div>
                </article>
              ))}
            </div>

            {selectedCategory === 'All' ? (
              <InfiniteScrollSentinel
                hasMore={hasMore}
                isLoadingMore={isLoadingMore}
                onLoadMore={loadMore}
              />
            ) : null}
          </DataStates>
        </div>
      </section>

      <section className="relative overflow-hidden bg-[oklch(0.22_0.07_343)] py-16 text-white sm:py-20">
        <div
          className="pointer-events-none absolute inset-0"
          style={{
            backgroundImage:
              'radial-gradient(ellipse 50% 45% at 20% 30%, oklch(0.50 0.09 179 / 0.3), transparent)',
          }}
          aria-hidden
        />
        <div className="container-wide relative">
          <div className="mx-auto max-w-2xl text-center">
            <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-accent">Next step</p>
            <span className="mx-auto mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
            <h2 className="mt-5 font-heading text-3xl sm:text-4xl">Ready to Join a Live Session?</h2>
            <p className="mx-auto mt-4 max-w-xl text-base leading-7 text-white/75">
              Contact us to discuss group bookings, custom cohorts, or to get notified when new live online
              programmes are scheduled.
            </p>
            <div className="mt-8 flex flex-col justify-center gap-3 sm:flex-row">
              <Link
                href="/contact?subject=live-online"
                className="inline-flex h-12 items-center justify-center gap-2 bg-accent px-7 text-sm font-semibold text-accent-foreground transition hover:bg-accent/90"
              >
                Enquire About Live Sessions
                <ArrowRight className="h-4 w-4" />
              </Link>
              <Link
                href="/services/upcoming-courses"
                className="inline-flex h-12 items-center justify-center border border-white/25 px-7 text-sm font-semibold transition hover:border-accent hover:text-accent"
              >
                Browse All Courses
              </Link>
            </div>
          </div>
        </div>
      </section>
    </>
  )
}

export default function LiveOnlineCoursesPage() {
  const t = useTranslations('training.liveOnline')
  return (
    <main>
      <PageHero
        eyebrow={t('hero.eyebrow')}
        title={t('hero.title')}
        description={t('hero.description')}
      />
      <Suspense
        fallback={
          <div className="container-wide py-20 text-center text-muted-foreground">
            Loading live online courses…
          </div>
        }
      >
        <LiveOnlineCoursesContent />
      </Suspense>
    </main>
  )
}
