'use client'

import { useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'
import { ArrowRight, Search } from 'lucide-react'
import { CourseCategoryCard } from '@/components/course-category-card'
import { DataStates } from '@/components/api/data-states'
import { InfiniteScrollSentinel } from '@/components/api/infinite-scroll-sentinel'
import { useFetchData } from '@/hooks/api'
import type { CourseCategory } from '@/lib/api/entities'
import { cn } from '@/lib/utils'

function isAiCategory(slug: string) {
  return /artificial-intelligence|artificial-intelligince|^ai$/.test(slug)
}

export default function CoursesPage() {
  const t = useTranslations('training.categories')
  const [query, setQuery] = useState('')
  const [view, setView] = useState<'grid' | 'directory'>('grid')

  const {
    items,
    isLoading,
    isError,
    isEmpty,
    error,
    refetch,
    loadMore,
    hasMore,
    isLoadingMore,
    pagination,
  } = useFetchData<CourseCategory>({
    endpoint: 'course-categories',
    infinite: true,
    initialPageSize: 12,
  })

  const categories = items ?? []
  const totalProgrammes = categories.reduce((sum, category) => sum + category.trainingCount, 0)

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase()
    if (!q) return categories
    return categories.filter(
      (category) =>
        category.name.toLowerCase().includes(q) ||
        category.description?.toLowerCase().includes(q) ||
        category.slug.toLowerCase().includes(q),
    )
  }, [categories, query])

  const sorted = useMemo(() => {
    return [...filtered].sort((a, b) => {
      const aAi = isAiCategory(a.slug)
      const bAi = isAiCategory(b.slug)
      if (aAi !== bAi) return aAi ? -1 : 1
      if (a.isFeatured !== b.isFeatured) return a.isFeatured ? -1 : 1
      return b.trainingCount - a.trainingCount
    })
  }, [filtered])

  const featured = sorted.filter((c) => c.isFeatured || isAiCategory(c.slug)).slice(0, 2)
  const featuredSlugs = new Set(featured.map((c) => c.slug))
  const rest = sorted.filter((c) => !featuredSlugs.has(c.slug))
  const [lead, ...secondary] = featured.length > 0 ? featured : sorted.slice(0, 1)
  const directory = featured.length > 0 ? rest : sorted.slice(1)

  return (
    <main>
      <section className="relative overflow-hidden bg-[oklch(0.22_0.07_343)] text-white">
        <div
          className="pointer-events-none absolute inset-0"
          style={{
            backgroundImage:
              'radial-gradient(ellipse 55% 50% at 90% 10%, oklch(0.50 0.09 179 / 0.35), transparent), radial-gradient(ellipse 40% 40% at 8% 90%, oklch(0.75 0.15 81 / 0.14), transparent)',
          }}
          aria-hidden
        />
        <div className="container-wide relative py-14 sm:py-16 md:py-20">
          <div className="grid gap-10 lg:grid-cols-[1.05fr_0.95fr] lg:items-end lg:gap-14">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-accent">{t('hero.eyebrow')}</p>
              <span className="mt-3 block h-0.5 w-10 bg-accent" aria-hidden />
              <h1 className="mt-5 font-heading text-4xl leading-snug sm:text-5xl md:text-[3.25rem]">
                {t('hero.title')}
              </h1>
              <p className="mt-4 max-w-xl text-base leading-7 text-white/72 sm:text-lg sm:leading-8">
                {pagination?.count
                  ? t('hero.descriptionCount', {
                      count: pagination.count,
                      programmes: totalProgrammes.toLocaleString(),
                    })
                  : t('hero.description')}
              </p>
              <dl className="mt-8 grid grid-cols-3 gap-4 border-t border-white/15 pt-6">
                <div>
                  <dt className="text-[10px] font-bold uppercase tracking-[0.14em] text-white/45">
                    {t('stats.disciplines')}
                  </dt>
                  <dd className="mt-1 font-heading text-2xl text-white sm:text-3xl">
                    {isLoading ? '—' : pagination?.count ?? categories.length}
                  </dd>
                </div>
                <div>
                  <dt className="text-[10px] font-bold uppercase tracking-[0.14em] text-white/45">
                    {t('stats.programmes')}
                  </dt>
                  <dd className="mt-1 font-heading text-2xl text-white sm:text-3xl">
                    {isLoading ? '—' : `${totalProgrammes.toLocaleString()}+`}
                  </dd>
                </div>
                <div>
                  <dt className="text-[10px] font-bold uppercase tracking-[0.14em] text-white/45">
                    {t('stats.focus')}
                  </dt>
                  <dd className="mt-1 font-heading text-2xl text-white sm:text-3xl">AI+</dd>
                </div>
              </dl>
            </div>

            <div className="border border-white/12 bg-white p-5 text-foreground sm:p-6">
              <p className="text-[11px] font-bold uppercase tracking-[0.18em] text-secondary">
                {t('search.eyebrow')}
              </p>
              <p className="mt-1 text-sm text-muted-foreground">
                {t('search.hint')}
              </p>
              <label className="relative mt-4 block">
                <span className="sr-only">{t('search.label')}</span>
                <Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <input
                  type="search"
                  value={query}
                  onChange={(event) => setQuery(event.target.value)}
                  placeholder={t('search.placeholder')}
                  className="h-12 w-full border border-border bg-[oklch(0.985_0.008_343)] pl-10 pr-4 text-sm outline-none transition placeholder:text-muted-foreground focus:border-primary focus:bg-white focus:ring-2 focus:ring-primary/20"
                  autoComplete="off"
                />
              </label>
              <div className="mt-4 flex flex-col gap-2 sm:flex-row">
                <Link
                  href="/services/upcoming-courses"
                  className="inline-flex h-11 flex-1 items-center justify-center gap-2 bg-primary px-4 text-sm font-semibold text-primary-foreground transition hover:bg-primary/90"
                >
                  {t('search.upcoming')}
                  <ArrowRight className="h-4 w-4" />
                </Link>
                <Link
                  href="/services/upcoming-courses?category=artificial-intelligence"
                  className="inline-flex h-11 flex-1 items-center justify-center border border-border px-4 text-sm font-semibold transition hover:border-primary hover:text-primary"
                >
                  {t('search.ai')}
                </Link>
              </div>
            </div>
          </div>
        </div>
        <div className="h-px bg-gradient-to-r from-transparent via-accent/70 to-transparent" />
      </section>

      <section className="border-b border-border/70 bg-[oklch(0.975_0.01_343)] py-14 sm:py-16 md:py-20">
        <div className="container-wide">
          <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                {t('browse.eyebrow')}
              </p>
              <span className="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">
                {t('browse.title')}
              </h2>
              <p className="mt-3 max-w-2xl text-base leading-7 text-muted-foreground">
                {t('browse.description')}
              </p>
            </div>

            <div className="flex items-center gap-2 self-start border border-border bg-white p-1">
              <button
                type="button"
                onClick={() => setView('grid')}
                className={cn(
                  'h-9 px-4 text-sm font-semibold transition',
                  view === 'grid'
                    ? 'bg-primary text-primary-foreground'
                    : 'text-muted-foreground hover:text-foreground',
                )}
                aria-pressed={view === 'grid'}
              >
                {t('browse.grid')}
              </button>
              <button
                type="button"
                onClick={() => setView('directory')}
                className={cn(
                  'h-9 px-4 text-sm font-semibold transition',
                  view === 'directory'
                    ? 'bg-primary text-primary-foreground'
                    : 'text-muted-foreground hover:text-foreground',
                )}
                aria-pressed={view === 'directory'}
              >
                {t('browse.directory')}
              </button>
            </div>
          </div>

          <DataStates
            isLoading={isLoading}
            isError={isError}
            isEmpty={isEmpty || sorted.length === 0}
            error={error}
            loadingMessage={t('loading')}
            emptyMessage={query.trim() ? t('emptySearch') : t('empty')}
            onRetry={refetch}
            skeleton={
              <div className="grid gap-4 md:grid-cols-2" aria-busy="true">
                <div className="min-h-[300px] animate-pulse bg-muted md:col-span-2" />
                {Array.from({ length: 4 }).map((_, i) => (
                  <div key={i} className="min-h-[280px] animate-pulse bg-muted" />
                ))}
              </div>
            }
          >
            {view === 'grid' ? (
              <div className="space-y-4">
                {lead ? <CourseCategoryCard category={lead} variant="featured" /> : null}

                <div className="grid auto-rows-fr grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                  {secondary.map((category) => (
                    <CourseCategoryCard
                      key={category.slug}
                      category={category}
                      variant="full"
                    />
                  ))}
                  {directory.map((category) => (
                    <CourseCategoryCard
                      key={category.slug}
                      category={category}
                      variant="full"
                    />
                  ))}
                </div>
              </div>
            ) : (
              <ul className="space-y-3">
                {sorted.map((category, index) => (
                  <li key={category.slug}>
                    <CourseCategoryCard
                      category={category}
                      variant="directory"
                      index={index + 1}
                    />
                  </li>
                ))}
              </ul>
            )}

            {!query.trim() ? (
              <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 15% 30%, oklch(0.50 0.09 179 / 0.3), transparent), radial-gradient(ellipse 40% 35% at 90% 80%, oklch(0.75 0.15 81 / 0.12), transparent)',
          }}
          aria-hidden
        />
        <div className="container-wide relative">
          <div className="grid gap-8 lg:grid-cols-[1.2fr_0.8fr] lg:items-center lg:gap-12">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-accent">Next step</p>
              <span className="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 Find Your Course?</h2>
              <p className="mt-4 max-w-xl text-base leading-7 text-white/75">
                Browse all upcoming courses or contact us for bespoke training tailored to your organisation.
              </p>
            </div>
            <div className="flex flex-col gap-3">
              <Link
                href="/services/upcoming-courses"
                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"
              >
                View Upcoming Courses
                <ArrowRight className="h-4 w-4" />
              </Link>
              <Link
                href="/services/bespoke-training"
                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"
              >
                Request bespoke training
              </Link>
              <Link
                href="/contact"
                className="inline-flex h-12 items-center justify-center text-sm font-semibold text-white/80 transition hover:text-accent"
              >
                Contact Us
              </Link>
            </div>
          </div>
        </div>
      </section>
    </main>
  )
}
