import { type FC, useMemo, useState } from "react";
import { DayTabButton } from "./DayTabButton.js";
import { DaySelect } from "./DaySelect.js";
import { generateDateRange, findPageIndex } from "./dateRange.js";
import "./DayTabs.scss";

const PAGE_SIZE = 7;

export interface DayTabsProps {
  selectedDate: string;
  availableDates: string[];
  daysBefore: number;
  daysAfter: number;
  locale: string;
  onNavigate: (date: string) => void;
}

export const DayTabs: FC<DayTabsProps> = ({
  selectedDate,
  availableDates,
  daysBefore,
  daysAfter,
  locale,
  onNavigate,
}) => {
  const allDates = useMemo(
    () => generateDateRange(new Date(), daysBefore, daysAfter),
    [daysBefore, daysAfter],
  );

  const totalPages = Math.max(1, Math.ceil(allDates.length / PAGE_SIZE));

  const initialPage = useMemo(
    () => findPageIndex(allDates, selectedDate, PAGE_SIZE),
    [allDates, selectedDate],
  );

  const [currentPage, setCurrentPage] = useState(initialPage);

  const availableSet = useMemo(() => new Set(availableDates), [availableDates]);

  const visibleDates = allDates.slice(
    currentPage * PAGE_SIZE,
    (currentPage + 1) * PAGE_SIZE,
  );

  const canGoPrev = currentPage > 0;
  const canGoNext = currentPage < totalPages - 1;

  return (
    <div className="day-tabs-wrap" data-testid="day-tabs">
      <div className="day-tabs">
        <button
          type="button"
          className="day-tabs__arrow"
          data-testid="day-tabs-prev"
          disabled={!canGoPrev}
          onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
          aria-label="Previous page"
        >
          {"\u2039"}
        </button>
        <div className="day-tabs__list">
          {visibleDates.map((date) => (
            <DayTabButton
              key={date}
              date={date}
              isActive={date === selectedDate}
              isDisabled={!availableSet.has(date)}
              locale={locale}
              onClick={onNavigate}
            />
          ))}
        </div>
        <button
          type="button"
          className="day-tabs__arrow"
          data-testid="day-tabs-next"
          disabled={!canGoNext}
          onClick={() => setCurrentPage((p) => Math.min(totalPages - 1, p + 1))}
          aria-label="Next page"
        >
          {"\u203a"}
        </button>
      </div>
      <DaySelect
        selectedDate={selectedDate}
        availableDates={availableDates}
        locale={locale}
        onNavigate={onNavigate}
      />
    </div>
  );
};
