'use client';

import { useState } from 'react';
import Link from 'next/link';
import { ChevronLeft, ChevronRight, ArrowRight } from 'lucide-react';
import { CategoryCard, type CategoryCardData } from '@/components/categories/CategoryCard';
import { Button } from '@/components/ui/button';
import { useLanguage } from '@/contexts/LanguageContext';
import { getCategoryTl } from '@/lib/categoryTl';
import { cn } from '@/lib/utils';

const PAGE_SIZE = 12;

interface CategoryBrowseSectionProps {
  categories: CategoryCardData[];
  viewAllHref: string;
  regionLabel?: string;
  variant?: 'default' | 'home';
}

export function CategoryBrowseSection({
  categories,
  viewAllHref,
  regionLabel,
  variant = 'default',
}: CategoryBrowseSectionProps) {
  const { lang, t } = useLanguage();
  const [page, setPage] = useState(0);
  const totalPages = Math.max(1, Math.ceil(categories.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages - 1);
  const start = safePage * PAGE_SIZE;
  const pageItems = categories.slice(start, start + PAGE_SIZE);

  const goTo = (next: number) => {
    setPage(Math.max(0, Math.min(next, totalPages - 1)));
  };

  if (variant === 'home') {
    return (
      <section className="home-trades px-4 py-12 md:py-16">
        <div className="mx-auto max-w-6xl">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between mb-8">
            <div>
              <span className="home-section-label">{t('Trades', 'Mga trabaho')}</span>
              <h2 className="home-section-title">
                {regionLabel
                  ? t(`Browse by trade in ${regionLabel}`, `Tingnan ang trabaho sa ${regionLabel}`)
                  : t('Browse by trade', 'Tingnan ayon sa trabaho')}
              </h2>
              <p className="mt-2 text-sm text-slate-600 max-w-xl">
                {t(
                  'Choose the skill you need — then see workers who do that work near you.',
                  'Piliin ang kasanayang kailangan mo — tapos tingnan ang workers na gumagawa nito malapit sa iyo.'
                )}
              </p>
            </div>
            <Link
              href={viewAllHref}
              className="inline-flex items-center gap-1.5 text-sm font-semibold text-slate-800 hover:text-[var(--home-amber)] transition-colors shrink-0"
            >
              {t(`All ${categories.length} trades`, `Lahat ng ${categories.length} trabaho`)}
              <ArrowRight className="h-3.5 w-3.5" />
            </Link>
          </div>

          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2.5 sm:gap-3">
            {pageItems.map((cat) => {
              const tl = getCategoryTl(cat.slug);
              const name = lang === 'tl' && tl?.nameTl ? tl.nameTl : cat.name;
              const workers = cat._count?.workerSkills ?? 0;

              return (
                <Link key={cat.id} href={`/category/${cat.slug}`} className="home-trade-tile group">
                  <span className="text-2xl leading-none" aria-hidden>
                    {cat.icon || '🔧'}
                  </span>
                  <span className="home-display text-sm font-bold text-slate-900 leading-snug line-clamp-2 group-hover:text-slate-950">
                    {name}
                  </span>
                  {workers > 0 ? (
                    <span className="mt-auto text-[11px] font-medium text-slate-500">
                      {t(
                        `${workers} worker${workers !== 1 ? 's' : ''}`,
                        `${workers} worker${workers !== 1 ? 's' : ''}`
                      )}
                    </span>
                  ) : (
                    <span className="mt-auto text-[11px] text-slate-400">
                      {t('View trade', 'Tingnan')}
                    </span>
                  )}
                </Link>
              );
            })}
          </div>

          {totalPages > 1 && (
            <div className="mt-8 flex flex-col sm:flex-row items-center justify-between gap-4">
              <p className="text-sm text-slate-500 tabular-nums">
                {t(
                  `Page ${safePage + 1} of ${totalPages}`,
                  `Pahina ${safePage + 1} ng ${totalPages}`
                )}
              </p>
              <div className="flex w-full sm:w-auto gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className="flex-1 sm:flex-none gap-1.5 rounded-none border-[#d6d0c4] bg-white"
                  onClick={() => goTo(safePage - 1)}
                  disabled={safePage === 0}
                >
                  <ChevronLeft className="h-4 w-4" />
                  {t('Previous', 'Previous')}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  className="flex-1 sm:flex-none gap-1.5 rounded-none border-[#d6d0c4] bg-white"
                  onClick={() => goTo(safePage + 1)}
                  disabled={safePage >= totalPages - 1}
                >
                  {t('Next', 'Next')}
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </div>
      </section>
    );
  }

  return (
    <section className="px-4 py-8 bg-surface border-y border-border">
      <div className="mx-auto max-w-6xl">
        <div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between mb-6">
          <div>
            <h2 className="section-heading">
              {regionLabel
                ? t(`Browse by Trade in ${regionLabel}`, `Tingnan ang mga trabaho sa ${regionLabel}`)
                : t('Browse by Trade', 'Tingnan ang mga Trabaho')}
            </h2>
            <p className="text-sm text-muted mt-1 max-w-xl">
              {t(
                'Pick a trade to see verified workers near you.',
                'Pumili ng trabaho para makita ang mga verified workers malapit sa iyo.'
              )}
            </p>
          </div>
          <Link href={viewAllHref} className="section-link shrink-0 mt-2 sm:mt-0">
            {t(`View all ${categories.length} trades`, `Tingnan ang ${categories.length} trabaho`)}
          </Link>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2.5 sm:gap-3">
          {pageItems.map((cat) => (
            <CategoryCard key={cat.id} category={cat} variant="compact" />
          ))}
        </div>

        {totalPages > 1 && (
          <div className="mt-6 flex flex-col items-center gap-4">
            <div className="flex items-center gap-1.5">
              {Array.from({ length: totalPages }).map((_, i) => (
                <button
                  key={i}
                  type="button"
                  aria-label={`Go to page ${i + 1}`}
                  onClick={() => goTo(i)}
                  className={cn(
                    'h-2 rounded-full transition-all',
                    i === safePage ? 'w-6 bg-slate-700' : 'w-2 bg-slate-300 hover:bg-slate-400',
                  )}
                />
              ))}
            </div>
            <div className="flex flex-col sm:flex-row items-center justify-center gap-3 w-full sm:w-auto">
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="gap-1.5 w-full sm:w-auto"
                onClick={() => goTo(safePage - 1)}
                disabled={safePage === 0}
              >
                <ChevronLeft className="h-4 w-4" />
                Previous
              </Button>
              <p className="text-sm text-muted tabular-nums text-center">
                Page {safePage + 1} of {totalPages}
                <span className="hidden sm:inline text-slate-400">
                  {' '}
                  · {start + 1}–{Math.min(start + PAGE_SIZE, categories.length)} of {categories.length}
                </span>
              </p>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="gap-1.5 w-full sm:w-auto"
                onClick={() => goTo(safePage + 1)}
                disabled={safePage >= totalPages - 1}
              >
                Next
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
