import {useEffect, useState} from "react";
import {NumericFormat} from "react-number-format";
import {Container, Typography} from "@mui/material";
import dayjs from "dayjs";

function Result({listEntry, baseSalary}) {
    const [totalOvertimePay, setTotalOvertimePay] = useState(0);
    const [holidayData, setHolidayData] = useState([[]]);
    const [fetched, setFetched] = useState([]);


    useEffect(() => {
        setTotalOvertimePay(getOvertimePayTotal(listEntry, baseSalary, holidayData));
    }, [listEntry, baseSalary, holidayData]);

    const fetchApi = (year) => {
        const baseUrl = 'https://dayoffapi.vercel.app/api';
        if (fetched.includes(year)) {
            return Promise.resolve();
        }
        return fetch(`${baseUrl}/?year=${year}`)
            .then((response) => response.json())
            .then((data) => {
                setHolidayData((currentData) => [...currentData, ...data]);
                setFetched((current) => [...current, year]);
            });
    }

    useEffect(() => {
        fetchApi(dayjs().year()).then(() => {});
        fetchApi(dayjs().year() - 1).then(() => {});
    }, []);

    if (totalOvertimePay < 0) {
        return (
                <Container>
                    <Typography variant='h5'>
                        Waktu selesai mendahului waktu mulai. Mohon diperbaiki input.
                    </Typography>
                </Container>
            )
    }

    return (
        <Container>
            <Typography variant='h5'>
                Total Upah Lembur: Rp<NumericFormat displayType="text" decimalScale={0} thousandSeparator={true}
                                                     value={totalOvertimePay}/>
            </Typography>
            <Typography>Rincian</Typography>
            { listEntry.map((entry) => {
                const holidayName = isHoliday(entry.date, holidayData);
                return (
                    <div key={entry.id}>
                        <Typography>
                            {entry.date.format('DD MMMM YYYY')}{holidayName ? ` (${holidayName})` : ''}: Rp<NumericFormat displayType="text" decimalScale={0} thousandSeparator={true} value={calculatePerDay(entry, baseSalary, holidayData)} />
                        </Typography>
                    </div>
                )
            }) }
        </Container>
    )
}

function segmentTime(duration, segments) {
    const segmentedHours = [];

    for (const[index, segmentDuration] of segments.entries()) {
        if (index < segments.length - 1) {
            const hours = Math.min(duration, segmentDuration.segment);
            segmentedHours.push(hours);
            duration -= hours;
        } else {
            segmentedHours.push(duration);
        }
    }
    return segmentedHours;
}

function isHoliday(date, holidayData) {
    if (date.day() === 0) {
        return 'Minggu';
    } else if (date.day() === 6) {
        return 'Sabtu';
    }
    let holidayName = '';
    if (holidayData) {
        console.log(holidayData);
        holidayData.every((day) => {
            if (dayjs(day['tanggal'], 'YYYY-MM-D').isSame(date, 'day')) {
                holidayName = day['keterangan'];
                return false;
            }
            return true;
        })
    }
    return holidayName;
}

function calculatePerDay(entry, baseSalary, holidayData) {
    const hourlyPay = baseSalary / 173;
    const overtimeDuration = entry.finish.diff(entry.start, 'hour', true);
    let multiplier = 0;

    const segmentMap = {
        workDays: [
            {segment: 1, multiplier: 1.5}, // jam pertama
            {segment: 23, multiplier: 2}
        ],
        holidays: [
            {segment: 8, multiplier: 2}, // 8 jam pertama
            {segment: 1, multiplier: 3}, // jam ke 9
            {segment: 15, multiplier: 4}
        ]
    }

    const segmentPattern = isHoliday(entry.date, holidayData) ? segmentMap.holidays : segmentMap.workDays;
    const segmentedDuration = segmentTime(overtimeDuration, segmentPattern);
    for (let i = 0; i < segmentedDuration.length; i++) {
        if (segmentedDuration[i])
            multiplier += segmentedDuration[i] * segmentPattern[i].multiplier;
    }

    return multiplier * hourlyPay;
}

function getOvertimePayTotal(listEntry, baseSalary, holidayData) {
    let total = 0;
    listEntry.forEach((entry) => {
        total += calculatePerDay(entry, baseSalary, holidayData)
    });
    return total;
}

export default Result;