import React from 'react';
import {
    setMonth,
    getMonth,
    setYear,
    getYear,
} from 'date-fns';
import { Grid, IconButton, MenuItem, Select } from '@mui/material';
import { ChevronLeft, ChevronRight } from '@mui/icons-material';

interface HeaderProps {
    date: Date;
    setDate: (date: Date) => void;
    nextDisabled: boolean;
    prevDisabled: boolean;
    onClickNext: () => void;
    onClickPrevious: () => void;
}

const MONTHS = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'June',
    'July',
    'Aug',
    'Sept',
    'Oct',
    'Nov',
    'Dec',
];

const generateYears = (relativeTo: Date, count: number) => {
    const half = Math.floor(count / 2);
    return Array(count)
        .fill(0)
        .map((_y, i) => relativeTo.getFullYear() - half + i);
};

export const Header: React.FunctionComponent<HeaderProps> = ({
    date, nextDisabled, prevDisabled,
    setDate, onClickNext, onClickPrevious,
}: HeaderProps) => {
    const handleMonthChange = (event: any) => {
        setDate(setMonth(date, parseInt(event.target.value)));
    };

    const handleYearChange = (event: any) => {
        setDate(setYear(date, parseInt(event.target.value)));
    };

    return (
        <Grid container justifyContent="space-between" alignItems="center">
            <Grid item style={{ padding: 5 }}>
                <IconButton
                    style={{ padding: 10 }}
                    disabled={prevDisabled}
                    onClick={onClickPrevious}
                >
                    <ChevronLeft color={prevDisabled ? 'disabled' : 'action'} />
                </IconButton>
            </Grid>
            <Grid item>
                <Select
                    variant="standard"
                    value={getMonth(date)}
                    onChange={handleMonthChange}
                    MenuProps={{ disablePortal: true }}
                >
                    {MONTHS.map((month, idx) => (
                        <MenuItem key={month} value={idx}>
                            {month}
                        </MenuItem>
                    ))}
                </Select>
            </Grid>

            <Grid item>
                <Select
                    variant="standard"
                    value={getYear(date)}
                    onChange={handleYearChange}
                    MenuProps={{ disablePortal: true }}
                >
                    {generateYears(date, 30).map((year) => (
                        <MenuItem key={year} value={year}>
                            {year}
                        </MenuItem>
                    ))}
                </Select>
            </Grid>
            <Grid item style={{ padding: 5 }}>
                <IconButton style={{ padding: 10 }} disabled={nextDisabled} onClick={onClickNext}>
                    <ChevronRight color={nextDisabled ? 'disabled' : 'action'} />
                </IconButton>
            </Grid>
        </Grid>
    );
}