'use client'

import { useTranslations } from 'next-intl'
import {
  ArrowRight,
  Building2,
  CalendarDays,
  Globe,
  HeartHandshake,
  Landmark,
  MapPin,
} 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 { SafeImage } from '@/components/safe-image'
import { Link } from '@/i18n/navigation'
import { useFetchData } from '@/hooks/api'
import type { ClientLogo } from '@/lib/api/entities'
import { resolveAssetPath } from '@/lib/asset-paths'
import { getYearsOfExcellence } from '@/lib/site-settings'
import { useSiteData } from '@/contexts/site-data-context'

const sectors = [
  { label: 'Banking & Finance', href: '/services/upcoming-courses?category=banking' },
  { label: 'Insurance', href: '/services/upcoming-courses?category=banking' },
  { label: 'Oil & Gas', href: '/services/upcoming-courses?category=oil-and-gas' },
  { label: 'Energy & Utilities', href: '/services/upcoming-courses?category=oil-and-gas' },
  { label: 'Mining & Metals', href: '/services/upcoming-courses?category=engineering' },
  { label: 'Manufacturing', href: '/services/upcoming-courses?category=engineering' },
  { label: 'Construction & Infrastructure', href: '/services/upcoming-courses?category=engineering' },
  { label: 'Real Estate', href: '/services/upcoming-courses?category=enterprise-development' },
  { label: 'Technology', href: '/services/upcoming-courses?category=technology' },
  { label: 'Artificial Intelligence & Digital Innovation', href: '/services/upcoming-courses?category=artificial-intelligence-ai' },
  { label: 'Telecommunications', href: '/services/upcoming-courses?category=information-technology' },
  { label: 'Healthcare', href: '/services/upcoming-courses?category=public-health' },
  { label: 'Pharmaceuticals', href: '/services/upcoming-courses?category=public-health' },
  { label: 'Education', href: '/services/upcoming-courses?category=training-of-trainers' },
  { label: 'Public Sector & Government', href: '/services/upcoming-courses?category=community-and-humanitarian-projects' },
  { label: 'Government & Regulatory Bodies', href: '/services/upcoming-courses?category=community-and-humanitarian-projects' },
  { label: 'Non-Governmental Organizations (NGOs)', href: '/services/upcoming-courses?category=community-and-humanitarian-projects' },
  { label: 'Development Partners & Donor Agencies', href: '/services/upcoming-courses?category=community-and-humanitarian-projects' },
  { label: 'Logistics & Supply Chain', href: '/services/upcoming-courses?category=procurement-and-contracts' },
  { label: 'Transportation', href: '/services/upcoming-courses?category=procurement-and-contracts' },
  { label: 'Aviation & Airports', href: '/services/upcoming-courses?category=engineering' },
  { label: 'Maritime & Ports', href: '/services/upcoming-courses?category=engineering' },
  { label: 'Agriculture & Agribusiness', href: '/services/upcoming-courses?category=environment-social-safeguard' },
  { label: 'Food & Beverage', href: '/services/upcoming-courses?category=food' },
  { label: 'Hospitality & Tourism', href: '/services/upcoming-courses?category=hotel' },
  { label: 'Retail & Consumer Goods', href: '/services/upcoming-courses?category=marketing-and-selling' },
  { label: 'FMCG', href: '/services/upcoming-courses?category=marketing-and-selling' },
  { label: 'Automotive', href: '/services/upcoming-courses?category=engineering' },
  { label: 'Media & Communications', href: '/services/upcoming-courses?category=communication' },
  { label: 'Legal Services', href: '/services/upcoming-courses?category=finance-and-audit' },
  { label: 'Customs & Trade', href: '/services/upcoming-courses?category=procurement-and-contracts' },
  { label: 'Defense & Security', href: '/services/upcoming-courses?category=community-and-humanitarian-projects' },
  { label: 'Water & Sanitation', href: '/services/upcoming-courses?category=environment-social-safeguard' },
  { label: 'Environment & Sustainability', href: '/services/upcoming-courses?category=environment-social-safeguard' },
  { label: 'Smart Cities', href: '/services/upcoming-courses?category=technology' },
] as const

export default function OurClientsPage() {
  const { site } = useSiteData()
  const t = useTranslations('about.clients')
  const years = getYearsOfExcellence(site.foundedYear)
  const metrics = site.clientMetrics
  const servePoints = t.raw('serve.points') as string[]
  const ctaPoints = t.raw('cta.points') as string[]

  const clientTypes = [
    {
      icon: Building2,
      key: 'corporates' as const,
      metric: `${metrics.fortune500}+`,
    },
    {
      icon: Globe,
      key: 'multinationals' as const,
      metric: `${metrics.government}+`,
    },
    {
      icon: Landmark,
      key: 'private' as const,
      metric: `${metrics.ngo}+`,
    },
    {
      icon: HeartHandshake,
      key: 'smes' as const,
      metric: `${metrics.regional}+`,
    },
  ]

  const {
    items,
    isLoading,
    isError,
    isEmpty,
    error,
    refetch,
    loadMore,
    hasMore,
    isLoadingMore,
    pagination,
  } = useFetchData<ClientLogo>({
    endpoint: 'client-logos',
    infinite: true,
    initialPageSize: 24,
  })

  const clientLogos = items ?? []
  const logoCount = pagination?.count ?? clientLogos.length
  const logoCountDisplay = isLoading ? '—' : `${logoCount}+`

  const stats = [
    { value: '15000+', label: t('stats.trained') },
    { value: '95%', label: t('stats.satisfaction') },
    { value: '85%', label: t('stats.repeat') },
    { value: logoCountDisplay, label: t('stats.logos') },
  ]

  return (
    <main>
      <PageHero
        eyebrow={t('hero.eyebrow')}
        title={t('hero.title')}
        description={t('hero.description')}
      />

      <section className="border-b border-border/70 bg-white">
        <div className="container-wide py-10 sm:py-12">
          <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
            {stats.map((stat) => (
              <div
                key={stat.label}
                className="border-l-2 border-accent/80 bg-[oklch(0.985_0.008_343)] px-5 py-6"
              >
                <p className="font-heading text-3xl text-primary sm:text-4xl">{stat.value}</p>
                <p className="mt-2 text-sm font-medium text-muted-foreground">{stat.label}</p>
              </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">
              {t('partnerships.eyebrow')}
            </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">
              {t('partnerships.title', { name: site.shortName })}
            </h2>
            <ul className="mx-auto mt-6 flex max-w-xl flex-col gap-3 text-left sm:items-center sm:text-center">
              <li className="inline-flex items-center gap-2.5 text-base text-muted-foreground sm:text-lg">
                <CalendarDays className="h-4 w-4 shrink-0 text-primary" />
                {t('partnerships.founded', { year: site.foundedYear })}
              </li>
              <li className="inline-flex items-center gap-2.5 text-base text-muted-foreground sm:text-lg">
                <Building2 className="h-4 w-4 shrink-0 text-primary" />
                {t('partnerships.years', { years })}
              </li>
              <li className="inline-flex items-center gap-2.5 text-base text-muted-foreground sm:text-lg">
                <MapPin className="h-4 w-4 shrink-0 text-primary" />
                {site.fullName}
              </li>
            </ul>
          </div>

          <DataStates
            isLoading={isLoading}
            isError={isError}
            isEmpty={isEmpty}
            error={error}
            loadingMessage={t('partnerships.loading')}
            emptyMessage={t('partnerships.empty')}
            onRetry={refetch}
          >
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
              {clientLogos.map((client) => (
                <div
                  key={client.id}
                  className="group flex h-28 items-center justify-center border border-border/80 bg-white p-4 transition duration-300 hover:border-secondary/40 hover:shadow-[0_12px_28px_rgba(15,23,42,0.06)] sm:h-32 sm:p-5"
                >
                  <div className="relative h-full w-full">
                    <SafeImage
                      src={resolveAssetPath(client.src)}
                      alt={client.name}
                      fill
                      sizes="(max-width: 640px) 45vw, (max-width: 1024px) 20vw, 160px"
                      quality={90}
                      unoptimized
                      className="object-contain object-center opacity-75 transition group-hover:opacity-100"
                      loading="lazy"
                      fallback={
                        <div className="flex h-full w-full items-center justify-center text-center text-xs font-semibold text-muted-foreground">
                          {client.name}
                        </div>
                      }
                    />
                  </div>
                </div>
              ))}
            </div>

            <InfiniteScrollSentinel
              hasMore={hasMore}
              isLoadingMore={isLoadingMore}
              onLoadMore={loadMore}
            />
          </DataStates>
        </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-10 max-w-2xl">
            <p className="text-[11px] font-bold uppercase tracking-[0.22em] text-secondary">
              {t('serve.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">{t('serve.title')}</h2>
            <ul className="mt-4 space-y-2 text-muted-foreground">
              {servePoints.map((point) => (
                <li key={point} className="flex gap-2">
                  <span className="mt-2 h-1.5 w-1.5 shrink-0 bg-primary" />
                  {point}
                </li>
              ))}
            </ul>
          </div>

          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            {clientTypes.map(({ icon: Icon, key, metric }) => (
              <div
                key={key}
                className="border border-border/80 bg-[oklch(0.985_0.008_343)] p-6 transition duration-300 hover:border-secondary/40 hover:bg-white hover:shadow-[0_16px_40px_rgba(15,23,42,0.06)]"
              >
                <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>
                <p className="font-heading text-3xl text-primary">{metric}</p>
                <h3 className="mt-3 text-lg font-bold text-foreground">
                  {t(`serve.types.${key}.title`)}
                </h3>
                <p className="mt-2 text-sm leading-6 text-muted-foreground">
                  {t(`serve.types.${key}.description`)}
                </p>
              </div>
            ))}
          </div>

          <div className="mt-12 border border-border/80 bg-[oklch(0.985_0.008_343)] p-6 sm:p-8">
            <h3 className="text-xl font-bold text-foreground">{t('serve.industriesTitle')}</h3>
            <p className="mt-2 text-sm text-muted-foreground">{t('serve.industriesDesc')}</p>
            <div className="mt-6 flex flex-wrap gap-2.5">
              {sectors.map((sector) => (
                <Link
                  key={sector.label}
                  href={sector.href}
                  className="border border-border bg-white px-4 py-2 text-sm font-medium text-foreground transition-colors hover:border-primary/40 hover:bg-primary/5 hover:text-primary"
                >
                  {sector.label}
                </Link>
              ))}
            </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="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), radial-gradient(ellipse 40% 35% at 90% 80%, oklch(0.75 0.15 81 / 0.12), transparent)',
          }}
          aria-hidden
        />
        <div className="container-wide relative text-center">
          <h2 className="font-heading text-3xl sm:text-4xl">{t('cta.title')}</h2>
          <ul className="mx-auto mt-5 flex max-w-xl flex-col gap-2 text-white/80 sm:items-center">
            {ctaPoints.map((point) => (
              <li key={point}>{point}</li>
            ))}
          </ul>
          <div className="mt-8 flex flex-col justify-center gap-3 sm:flex-row">
            <Link
              href="/contact"
              className="inline-flex h-12 items-center justify-center gap-2 bg-accent px-8 text-sm font-semibold text-accent-foreground transition hover:bg-accent/90"
            >
              {t('cta.contact')}
              <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-8 text-sm font-semibold transition hover:border-accent hover:text-accent"
            >
              {t('cta.courses')}
            </Link>
          </div>
        </div>
      </section>
    </main>
  )
}
