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

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

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 weekendDay(date) {
    if (date.day() === 0) {
        return 'Minggu';
    } else if (date.day() === 6) {
        return 'Sabtu';
    }
    return '';
}

function calculatePerDay(entry, baseSalary) {
    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 segmentedDuration = segmentTime(overtimeDuration, [1]);
    const usedMap = weekendDay(entry.date) ? multiplierMap.holidays : multiplierMap.workDays;
    for (let i = 0; i < segmentedDuration.length; 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;