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

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

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

    return (
        <Container>
            <Typography variant='h6'>
                Total Upah Lembur: Rp<NumericFormat displayType="text" decimalScale={0} thousandSeparator={true}
                                                     value={totalOvertimePay}/>
            </Typography>
            {/*{listEntry.map((entry) => {*/}
            {/*    return (*/}
            {/*        <div key={entry.id}>*/}
            {/*            <p>*/}
            {/*                {entry.date.format('DD MMMM YYYY')} dapetnya Rp<NumericFormat displayType="text" decimalScale={0} thousandSeparator={true} value={calculatePerDay(entry, baseSalary)} />*/}
            {/*            </p>*/}
            {/*        </div>*/}
            {/*    )*/}
            {/*})}*/}
        </Container>
    )
}

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

    // TODO: hmm... Adakah cara yg lebih cerdas dari ini?
    const multiplierMap = {
        workDays: {
            oneHour: 1.5,
            moreHours: 3.5 // 1.5 + 2
        },
        holidays: {
            eightHours: 2,
            nineHours: 5, // 2 + 3
            moreHours: 9 // 2 + 3 + 4
        }
    }

    const isWeekend = entry.date.day() === 0 || entry.date.day() === 6; // 0: Minggu, 6: Sabtu
    // Jelek bgt buset
    if (isWeekend) {
        // Kerja di hari libur. Temennya Yohana wkwk
        if (0 < overtimeDuration <= 8) {
            multiplier = multiplierMap.holidays.eightHours;
        } else if (8 < overtimeDuration <= 9){
            multiplier = multiplierMap.holidays.nineHours;
        } else {
            multiplier = multiplierMap.holidays.moreHours;
        }
    } else {
        // Lembur hari kerja
        if (0 < overtimeDuration <= 8) {
            multiplier = multiplierMap.workDays.oneHour;
        } else {
            multiplier = multiplierMap.workDays.moreHours;
        }
    }

    return multiplier * overtimeDuration * hourlyPay;
}

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

export default Result;