/* eslint-disable no-plusplus */ /* eslint-disable @typescript-eslint/no-shadow */ /* eslint-disable react/no-array-index-key */ /* eslint-disable jsx-a11y/label-has-associated-control */ import dayjs from "dayjs"; import React, { useEffect, useState } from "react"; import { Button } from "@/components/ui/button/button"; import { useLocale } from "@/hooks/useLocale"; interface Month { name: string; index: number; year: number; } interface SelectedMonth { month: string | undefined; defaultMonthName: string; fullDate: string | undefined; anySelected: boolean; date?: { from?: any; to?: any; }; } export interface PeriodPickerProps { onPeriodSelect: (selectedPeriod: SelectedMonth) => void; } const PeriodPicker = (props: PeriodPickerProps) => { const { t } = useLocale(); const [anySelected, setAnySelected] = useState(false); const [selectedMonth, setSelectedMonth] = useState({ month: "", defaultMonthName: "", fullDate: "", anySelected: true, }); const [nextMonthsByYear, setNextMonthsByYear] = useState<{ [year: string]: Month[]; }>({}); const calculateNextMonths = (): Record => { const today = dayjs(); const currentMonth = today.month(); const currentYear = today.year(); const months: Month[] = []; let year = currentYear; let month = currentMonth + 1; for (let i = 0; i < 12; i++) { if (month > 12) { month = 1; year++; } const monthName = today.month(month - 1).format("MMM"); months.push({ name: monthName, index: month - 1, year, }); month++; } const monthsByYear = months.reduce( (acc: Record, month) => { if (!acc[month.year]) { acc[month.year] = []; } acc[month.year]!.push(month); return acc; }, {} as Record, ); return monthsByYear; }; useEffect(() => { const monthsByYear = calculateNextMonths(); setNextMonthsByYear(monthsByYear); }, []); const handleMonthSelection = (month: Month): void => { setAnySelected(false); const firstDayOfMonth = dayjs(`${month.year}-${month.index + 1}-01`); const lastDayOfMonth = firstDayOfMonth.endOf("month"); const selectedPeriod: SelectedMonth = { month: month.name, defaultMonthName: "", fullDate: dayjs(`${month.year}-${month.index + 1}-01`).format(), anySelected: false, date: { from: firstDayOfMonth, to: lastDayOfMonth, }, }; props.onPeriodSelect(selectedPeriod); setSelectedMonth(selectedPeriod); }; const anySelectedFunc = (): void => { setAnySelected(true); const selectedPeriod: SelectedMonth = { month: undefined, defaultMonthName: t("Any Period"), fullDate: undefined, anySelected: true, }; setSelectedMonth(selectedPeriod); props.onPeriodSelect(selectedPeriod); }; return (
{Object.keys(nextMonthsByYear).map((year) => (

{year}

    {(nextMonthsByYear[year] || []).map((month, index) => (
  • ))}
))}
); }; export default PeriodPicker;