import React, {ReactNode, useContext, useEffect, useState} from 'react';
import PageTitle from "../UI/Typography/PageTitle";
import dayjs, {Dayjs} from "dayjs";
import {getTimesheetMonth, postTimeSheet} from "../../API/timesheets";
import MonthlyTimesheet from "./MonthlyTimesheet";
import {TimesheetMonth} from "../../models/timesheets";
import AuthContext from "../../context/auth-context";
import useLoading from "../../hooks/useLoading";


type TimeSheetsProps = {
    children?: ReactNode
}

function downloadFromByteArray(reportName: string, byte: any) {
    var blob = new Blob([byte], {type: "application/pdf"});
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    var fileName = reportName;
    link.download = fileName;
    link.click();
}


const TimeSheets = ({children}: TimeSheetsProps) => {

    const [timesheetTarget, setTimesheetTarget] = useState<{
        year:  number | null
        month: number | null
    }>({
        year: dayjs().year(),
        month: null,
    })

    const [timesheetMonth, setTimesheetMonth] = useState<TimesheetMonth>()
    const {currentUser} = useContext(AuthContext)
    const [loading, setLoading] = useLoading(true)

    const setDayContent = (week: number, day: number, content: string) => {
        if (!timesheetMonth) return
        const newTimeSheetMonth = JSON.parse(JSON.stringify(timesheetMonth))
        newTimeSheetMonth[week - 1][day - 1]['content'] = content
        setTimesheetMonth(newTimeSheetMonth)


    }


    const saveTimeSheet = async () => {
        const timeSheetContent = timesheetMonth?.map(week =>
            week.map(day => day.content)
        );

        const { month, year } = timesheetTarget;

        // Ensure `month` is treated as part of a valid date
        const validDate = dayjs(`${year}-${month}-01`, 'YYYY-M-DD');

        const res = await postTimeSheet({
            month,
            year,
            timesheet: timesheetMonth,
        });

        const pdfName = `${currentUser?.firstname} ${currentUser?.lastname} - ${validDate.locale('el').format('MMMM YYYY').toUpperCase()}.pdf`;

        downloadFromByteArray(pdfName, res.data);

    };


    useEffect(() => {





        (async () => {
            if (!(timesheetTarget.month && timesheetTarget.year)) return


            const targetString = `${timesheetTarget.year.toString()}-${timesheetTarget.month.toString().padStart(2, '0')}-01`;



            setLoading(true, true)

            const res = await getTimesheetMonth(targetString)
            setLoading(false)
            setTimesheetMonth(res.data.timesheet_month)

        })()

    }, [timesheetTarget.month])

    return (
        <div>
            <PageTitle>Monthly Timesheets</PageTitle>


            <div className={'d-flex gap-5 mb-5'}>

                {/* <button className={`nav-item ${timesheetTarget.year === 2024 && 'active'}`}
                        onClick={() => setTimesheetTarget({
                            year: 2024,
                            month: null
                        })}>
                    2024
                </button> */}


                <button className={`nav-item`}>
                    {timesheetTarget.year}
                </button>

            </div>

            {
                timesheetTarget.year &&
                <div className={"months-nav"}>
                    {
                        new Array(12).fill(null).map((_, i) =>
                            <button key={i} className={'nav-item'}
                                    onClick={() => setTimesheetTarget({
                                        ...timesheetTarget,
                                        month: i+1,
                                    })}>
                                {dayjs().month(i).locale('el-GR').format('MMMM')}
                            </button>
                        )}
                </div>
            }


            {
                timesheetTarget.month &&
                <>
                    {/*<PageTitle>{dayjs(month).locale('el-GR').format('MMMM YYYY')}</PageTitle>*/}
                    {
                        timesheetMonth &&
                        <MonthlyTimesheet
                            month={timesheetMonth}
                            setDayContent={setDayContent}
                            saveTimeSheet={saveTimeSheet}
                        />
                    }
                </>
            }
        </div>
    )
}

export default TimeSheets;

