'use client';

import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';

export const generatePagination = (availableYears: number[], currentYear:number) => {

  const [firstYear, secondYear, thirdYear] = availableYears;
  const [lastYear, yearBeforeLast1, yearBeforeLast2] = [...availableYears].reverse();
  const currentYearIndex = availableYears.indexOf(currentYear);

  // If the current year is among the first 3 years,
  // show the first 3 and ellipsis
  if (currentYearIndex < 2) {
    return [firstYear, secondYear, thirdYear, '...'];
  }

  // If the current year is among the last 2 years,
  // ellipsis and last 3 years.
  if (currentYearIndex > availableYears.length - 3) {
    return ['...', yearBeforeLast2, yearBeforeLast1, lastYear];
  }

  // If the current year is somewhere in the middle,
  // show the first year, an ellipsis, the current year and its neighbors,
  // another ellipsis, and the last year.
  return [
    '...',
    availableYears[currentYearIndex - 1],
    currentYear,
    availableYears[currentYearIndex + 1],
    '...',
  ];
};

export default function Pagination({ availableYears } : { availableYears: number[] }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  // don't show pagination if there's less than 2 years available
  if(availableYears.length < 2) {
    return null;
  }

  const showAllPages = availableYears.length < 5;

  const createYearURL = (yearNumber: number | string | undefined) => {
    if(!yearNumber) return "/";

    const params = new URLSearchParams(searchParams);
    params.set('year', yearNumber.toString());
    return `${pathname}?${params.toString()}`;
  }

  const currentYear = Number(searchParams.get('year')) || 1;
  
  const selectedYears = showAllPages ? availableYears : generatePagination(availableYears, currentYear);

  const latestYear = availableYears[0];
  const earliestYear = availableYears[availableYears.length-1];

  return (
    <>
      <div className="join">
        {
          // If there are more than 3 years, show the left arrow.
          !showAllPages &&
            <YearArrow
              direction="left"
              href={createYearURL(latestYear)}
              isDisabled={currentYear === latestYear}
            />
        }

        <div className="flex -space-x-px">
          {selectedYears.map((year, index) => {
            let position: 'first' | 'last' | 'single' | 'middle' | undefined;

            if (index === 0) position = 'first';
            if (index === selectedYears.length - 1) position = 'last';
            if (selectedYears.length === 1) position = 'single';
            if (year === '...') position = 'middle';

            return (
              <YearNumber
                key={`${year}-${index}`}
                href={createYearURL(year)}
                year={year}
                position={position}
                isActive={currentYear === year}
              />
            );
          })}
        </div>

        {
          // If there are more than 3 years, show the left arrow.
          !showAllPages &&
          <YearArrow
            direction="right"
            href={createYearURL(earliestYear)}
            isDisabled={currentYear === earliestYear}
            />
        }

      </div>
    </>
  );
}

function YearNumber({
  year,
  href,
  isActive,
  position,
}: {
  year: number | string;
  href: string;
  position?: 'first' | 'last' | 'middle' | 'single';
  isActive: boolean;
}) {
  return(<Link href={href} className={`join-item btn ${ isActive ? 'btn-active' : '' } ${ position === 'middle' ? 'btn-disabled' : '' }`}>{year}</Link>);
}

function YearArrow({
  href,
  direction,
  isDisabled,
}: {
  href: string;
  direction: 'left' | 'right';
  isDisabled?: boolean;
}) {

  const icon = direction === 'left' ? "⏴" : "⏵";
  return (<Link className={`join-item btn ${isDisabled ? "btn-disabled" : ""}`} href={href}>{icon}</Link>);
}
