'use client'

import { useEffect, useMemo, useState } from 'react'
import Image from 'next/image'
import { useTranslations } from 'next-intl'
import { ArrowRight, Camera, Users } from 'lucide-react'
import { PageHero } from '@/components/page-hero'
import { GalleryGrid } from '@/components/gallery-grid'
import { Button } from '@/components/ui/button'
import { DataStates } from '@/components/api/data-states'
import { InfiniteScrollSentinel } from '@/components/api/infinite-scroll-sentinel'
import { Link } from '@/i18n/navigation'
import { useFetchData } from '@/hooks/api'
import { apiRequest } from '@/lib/api/client'
import type { GalleryImage } from '@/lib/api/entities'
import { resolveAssetPath } from '@/lib/asset-paths'
import { getYearsOfExcellence } from '@/lib/site-settings'
import { useSiteData } from '@/contexts/site-data-context'
import { cn } from '@/lib/utils'

type YearFilter = 'all' | number

function groupImagesByYear(images: GalleryImage[]) {
  const groups = new Map<number, GalleryImage[]>()

  for (const image of images) {
    const year = image.year
    const existing = groups.get(year)
    if (existing) {
      existing.push(image)
    } else {
      groups.set(year, [image])
    }
  }

  return [...groups.entries()].sort(([a], [b]) => b - a)
}

export default function GalleryPage() {
  const { site } = useSiteData()
  const t = useTranslations('about.gallery')
  const years = getYearsOfExcellence(site.foundedYear)
  const [selectedYear, setSelectedYear] = useState<YearFilter>('all')
  const [availableYears, setAvailableYears] = useState<number[]>([])
  const introPoints = (t.raw('intro.points') as string[]).map((point) =>
    point.replace('{year}', String(site.foundedYear)),
  )

  useEffect(() => {
    let cancelled = false

    void apiRequest<{ data?: number[] } | number[]>('gallery-images/years/')
      .then((result) => {
        if (cancelled) return
        const years = Array.isArray(result)
          ? result
          : Array.isArray(result?.data)
            ? result.data
            : []
        setAvailableYears(years.map(Number).filter((year) => Number.isFinite(year)))
      })
      .catch(() => {
        if (!cancelled) setAvailableYears([])
      })

    return () => {
      cancelled = true
    }
  }, [])

  const yearParams = useMemo(
    () => (selectedYear === 'all' ? undefined : { year: selectedYear }),
    [selectedYear],
  )

  const {
    items,
    isLoading,
    isError,
    isEmpty,
    error,
    refetch,
    loadMore,
    hasMore,
    isLoadingMore,
    pagination,
  } = useFetchData<GalleryImage>({
    endpoint: 'gallery-images',
    infinite: true,
    initialPageSize: 24,
    params: yearParams,
  })

  const galleryImages = items ?? []
  const dedupedGalleryImages = useMemo(() => {
    const seen = new Set<string>()
    const unique: GalleryImage[] = []
    for (const img of galleryImages) {
      const resolvedSrc = resolveAssetPath(img.src)
      const key = resolvedSrc || img.src
      if (!key || seen.has(key)) continue
      seen.add(key)
      unique.push(img)
    }
    return unique
  }, [galleryImages])

  const featuredImages = useMemo(() => {
    const arr = dedupedGalleryImages
    if (arr.length <= 6) return arr.slice(0, 6)
    const count = 6
    const indices = Array.from({ length: count }, (_, i) =>
      Math.round((i * (arr.length - 1)) / (count - 1)),
    )
    return indices.map((idx) => arr[idx]).filter(Boolean) as GalleryImage[]
  }, [dedupedGalleryImages])
  const imageCount = dedupedGalleryImages.length
  const showGallerySummary = !isLoading && !isError && featuredImages.length > 0
  const yearGroups = useMemo(
    () => groupImagesByYear(dedupedGalleryImages),
    [dedupedGalleryImages],
  )
  const yearTabs = useMemo(() => {
    const fromApi = availableYears.length
      ? availableYears
      : yearGroups.map(([year]) => year)
    return [...new Set(fromApi)].sort((a, b) => b - a)
  }, [availableYears, yearGroups])

  return (
    <main>
      <PageHero
        eyebrow={t('hero.eyebrow')}
        title={t('hero.title')}
        description={t('hero.description', { name: site.shortName, years })}
      />

      <section className="border-b border-border/70 bg-[oklch(0.975_0.01_343)]">
        <div className="container-wide py-10">
          <div className="grid gap-6 lg:grid-cols-[1.1fr_0.9fr] lg:items-center">
            <div>
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                {t('intro.eyebrow')}
              </p>
              <h2 className="mt-3 font-heading text-3xl text-foreground sm:text-4xl">
                {isLoading
                  ? t('intro.loading')
                  : t('intro.moments', { count: imageCount })}
              </h2>
              <ul className="mt-4 max-w-2xl space-y-2 text-base text-muted-foreground">
                {introPoints.map((point) => (
                  <li key={point} className="flex gap-2">
                    <span className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-primary" />
                    {point}
                  </li>
                ))}
              </ul>
            </div>

            <div className="grid grid-cols-3 gap-2 sm:gap-3">
              {showGallerySummary
                ? featuredImages.map((image) => (
                    <div
                      key={image.id}
                      className="overflow-hidden border border-border/80 bg-white"
                    >
                      <Image
                        src={resolveAssetPath(image.src)}
                        alt={image.alt}
                        width={400}
                        height={300}
                        sizes="(max-width: 640px) 33vw, 200px"
                        quality={60}
                        className="aspect-[4/3] h-full w-full object-cover"
                        loading="lazy"
                      />
                    </div>
                  ))
                : Array.from({ length: 6 }).map((_, index) => (
                    <div
                      key={index}
                      className="aspect-[4/3] animate-pulse border border-border/80 bg-muted"
                    />
                  ))}
            </div>
          </div>
        </div>
      </section>

      <section className="border-b border-border/70 bg-white py-16 sm:py-20 md:py-24">
        <div className="container-wide">
          <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
            <div className="max-w-2xl">
              <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
                {t('grid.eyebrow')}
              </p>
              <h2 className="mt-3 font-heading text-3xl text-foreground">{t('grid.title')}</h2>
              <p className="mt-3 text-muted-foreground leading-7">{t('grid.description')}</p>
            </div>
            <p className="text-sm font-medium text-muted-foreground">
              {t('grid.photos', { count: imageCount })}
            </p>
          </div>

          {yearTabs.length > 0 ? (
            <div className="mb-10 flex flex-wrap gap-2">
              <button
                type="button"
                onClick={() => setSelectedYear('all')}
                className={cn(
                  'inline-flex h-10 items-center border px-4 text-sm font-semibold transition',
                  selectedYear === 'all'
                    ? 'border-primary bg-primary text-primary-foreground'
                    : 'border-border bg-white text-muted-foreground hover:border-secondary hover:text-foreground',
                )}
              >
                {t('grid.allYears')}
              </button>
              {yearTabs.map((year) => (
                <button
                  key={year}
                  type="button"
                  onClick={() => setSelectedYear(year)}
                  className={cn(
                    'inline-flex h-10 items-center border px-4 text-sm font-semibold transition',
                    selectedYear === year
                      ? 'border-primary bg-primary text-primary-foreground'
                      : 'border-border bg-white text-muted-foreground hover:border-secondary hover:text-foreground',
                  )}
                >
                  {year}
                </button>
              ))}
            </div>
          ) : null}

          <DataStates
            isLoading={isLoading}
            isError={isError}
            isEmpty={isEmpty}
            error={error}
            loadingMessage={t('grid.loading')}
            emptyMessage={t('grid.empty')}
            onRetry={refetch}
          >
            {selectedYear === 'all' ? (
              <div className="space-y-12">
                {yearGroups.map(([year, images]) => (
                  <div key={year}>
                    <div className="mb-5 flex items-end justify-between gap-3 border-b border-border/50 pb-3">
                      <h3 className="text-2xl font-bold text-foreground">{year}</h3>
                      <p className="text-sm text-muted-foreground">
                        {t('grid.photos', { count: images.length })}
                      </p>
                    </div>
                    <GalleryGrid images={images} />
                  </div>
                ))}
              </div>
            ) : (
              <GalleryGrid images={dedupedGalleryImages} />
            )}
            <InfiniteScrollSentinel
              hasMore={hasMore}
              isLoadingMore={isLoadingMore}
              onLoadMore={loadMore}
            />
          </DataStates>
        </div>
      </section>

      <section className="border-b border-border/70 bg-[oklch(0.975_0.01_343)] py-16 sm:py-20">
        <div className="container-wide">
          <div className="grid gap-5 md:grid-cols-2">
            {(
              [
                { icon: Camera, key: 'live' as const },
                { icon: Users, key: 'participants' as const },
              ] as const
            ).map(({ icon: Icon, key }) => (
              <div key={key} className="border border-border/80 bg-white p-6">
                <div className="mb-4 flex h-11 w-11 items-center justify-center bg-primary/8 text-primary">
                  <Icon className="h-5 w-5" />
                </div>
                <h3 className="text-lg font-bold text-foreground">
                  {t(`highlights.${key}.title`)}
                </h3>
                <p className="mt-2 text-sm leading-6 text-muted-foreground">
                  {t(`highlights.${key}.description`)}
                </p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="relative overflow-hidden bg-[oklch(0.22_0.07_343)] py-16 text-white sm:py-20">
        <div className="container-wide text-center">
          <h2 className="font-heading text-3xl sm:text-4xl">
            {t('cta.title', { name: site.shortName })}
          </h2>
          <p className="mx-auto mt-4 max-w-2xl text-white/80 leading-7">
            {t('cta.description')}
          </p>
          <div className="mt-8 flex flex-col justify-center gap-4 sm:flex-row">
            <Link href="/services/upcoming-courses">
              <Button
                size="lg"
                className="h-12 bg-accent px-8 font-semibold text-accent-foreground hover:bg-accent/90"
              >
                {t('cta.browse')}
                <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </Link>
            <Link href="/contact">
              <Button size="lg" variant="outlineLight" className="h-12 px-8 font-semibold">
                {t('cta.contact')}
              </Button>
            </Link>
          </div>
        </div>
      </section>
    </main>
  )
}
