import { CaretLeftFilled, CaretRightFilled } from '@ant-design/icons';
import { Select } from 'antd';
import React from 'react';

import './calendar.css';

const dayAr = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const monthAr = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
];

export default function CalendarComp() {

    let lastDate = new Date();

    const [month, setMonth] = React.useState(lastDate.getMonth());
    const [year, setYear] = React.useState(lastDate.getFullYear());
    const [selectedDate, setSelectedDate] = React.useState();

    function calendarNodeLoop() {
        let Nodes = [];

        lastDate.setMonth(month);
        lastDate.setDate(31);
        if (lastDate.getMonth() !== 1 && lastDate.getDate() === 1) {
            lastDate.setDate(30);
        }

        if (lastDate.getDate() === 3 || lastDate.getDate() === 2) {
            //chech for leap year and set date to 29 if true else 28
            (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
                ? lastDate.setDate(29)
                : lastDate.setDate(28);
        }

        for (let i = 1; i <= lastDate.getDate(); i++) {
            const dateObj = new Date();
            dateObj.setMonth(month);
            dateObj.setFullYear(year);
            dateObj.setDate(i);
            Nodes.push(
                <Calendar
                    key={dateObj}
                    day={dayAr[dateObj.getDay()]}
                    date={dateObj.getDate()}
                    month={month}
                    year={year}
                    setSelectedDate={setSelectedDate}
                    selectedDate={selectedDate}
                />
            );
        }
        return Nodes;
    }

    React.useEffect(() => {
        setTimeout(() => {
            const todayDiv = document.querySelector('.today');
            if (todayDiv) {
                todayDiv.scrollIntoView({ behavior: 'smooth', block: "nearest", inline: 'start' });
            }
        }, 0);
    }, []);

    // this is to make an array with numbers starting from 'start' to 'end'.
    function range(start, end) {
        return Array(end - start + 1)
            .fill()
            .map((_, idx) => start + idx);
    }

    function handlerMonth (val) {
        setMonth(() => val);
    }

    function handlerYear (val) {
        setYear(() => val);
    }

    function scrollStrip(direction) {
        const strip = document.querySelector('.strip');
        if(strip) {
            direction === "left"? strip.scrollTo({left: strip.scrollLeft - 50, behavior: 'smooth'}) 
                : strip.scrollTo({left: strip.scrollLeft + 50, behavior: 'smooth'});
        }
    }

    return (
        <div
            className="calendar-strip"
            style={{
                position: 'relative',
                backgroundColor: '#3b3cea',
                borderRadius: '12px',
                color: 'white',
            }}
        >
            <div
                className="calendar-context pr-2-0"
                style={{
                    width: '100%',
                    display: 'flex',
                    justifyContent: 'flex-end',
                    paddingBlock: '8px',
                    gap: '10px',
                }}
            >
                <Select name="month" id="month" onChange={handlerMonth} value={month}>
                    {monthAr.map((item, i) => (
                        <Select.Option key={i} value={i}>
                            {item}
                        </Select.Option>
                    ))}
                </Select>
                <Select name="year" id="year" onChange={handlerYear} value={year}>
                    {range(2020, 2050).map((item) => (
                        <Select.Option key={item} value={item}>
                            {item}
                        </Select.Option>
                    ))}
                </Select>
            </div>

            <div
                className="strip py-0-5 px-1-0"
                style={{
                    // height: '85px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'flex-start',
                    overflowX: 'auto',
                    gap: '3px',
                    marginInline: '25px'
                }}
            >
                <CaretLeftFilled style={{ position: 'absolute', left: '5px' }} onClick={() => scrollStrip("left")} />
                <CaretRightFilled style={{ position: 'absolute', right: '5px' }} onClick={() => scrollStrip("right")} />
                {calendarNodeLoop()}
            </div>
        </div>
    );
}

function Calendar({ date, day, month, year, setSelectedDate, selectedDate }) {
    const dateToday = new Date();
    let classString = "calendar-node";
    let childClass = "";

    if (selectedDate) {
        const split = selectedDate.split('/');

        if( date === parseInt(split[0], 10) && month === parseInt(split[1], 10) && year === parseInt(split[2], 10) ) {
            classString = "calendar-node selected";
        }
    }

    if (dateToday.getDate() === date && dateToday.getMonth() === month && dateToday.getFullYear() === year) {
        classString = "calendar-node today"
    }

    return (
        <div
            className={classString}
            style={{
                minHeight: '60px',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100%',
                flex: '1 0 50px',
            }}
            onClick={() => {
                setSelectedDate(() => `${date}/${month}/${year}`);
            }}
        >
            <div style={{ opacity: '70%', lineHeight: 1.2 }}>{day}</div>
            <div style={{ fontSize: '1.8rem', lineHeight: 1.2 }}>{date}</div>
        </div>
    );
}