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([]);

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

    useEffect(() => {
        fetchApi(dayjs().year()).then((result) => {
            setHolidayData((currentData) => [...currentData, {year: dayjs().year(), data: result}]);
        });
    }, []);

    useEffect(() => {
        console.log(holidayData);
    }, [holidayData]);

    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) => {
                return (
                    <div key={entry.id}>
                        <Typography>
                            {entry.date.format('DD MMMM YYYY')}{isHoliday(entry.date) ? ` (${isHoliday(entry.date)})` : ''}: Rp<NumericFormat displayType="text" decimalScale={0} thousandSeparator={true} value={calculatePerDay(entry, baseSalary)} />
                        </Typography>
                    </div>
                )
            }) }
        </Container>
    )
}

function fetchApi(year) {
    // kemungkinan nanti ada pengecekan taun udah pernah difetch / belum
    const baseUrl = 'https://dayoffapi.vercel.app/api';
    return fetch(`${baseUrl}/?year=${year}`)
        .then((response) => response.json())
        .then((data) => data);
}

function segmentTime(duration, segments) {
    const segmentSum = segments.reduce((partialSum, a) => partialSum + a, 0);
    const segmentsFilled = [...segments, 24 - segmentSum];
    const segmentedHours = [];

    for (const[index, segmentDuration] of segmentsFilled.entries()) {
        if (index < segmentsFilled.length - 1) {
            const hours = Math.min(duration, segmentDuration);
            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';
    }


    return '';
}

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

    // TODO: find better way
    const multiplierMap = {
        workDays: [
            1.5, // jam pertama
            2
        ],
        holidays: [
            2, // 8 jam pertama
            3, // jam ke 9
            4
        ]
    }

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

    return multiplier * hourlyPay;
}

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

export default Result;