import React, {useEffect, useState} from 'react';
import {Select, Space} from 'antd';
import dayjs from 'dayjs';
import {useDispatch, useSelector} from "react-redux";
import {getArchiveSchedule, insertArchiveSchedule} from "../httpServices/httpServiceArchiveSchedule";
import {isEmpty} from "../actions/settingActions";
import {destroyAlerts, errorAlert, savedAlert, savingAlert} from "../actions/alertActions";
import {saveLog} from "../httpServices/httpServiceLog";
const ArchiveScheduleDate = () => {
    const {archiveSchedule, loading, error} = useSelector(state => state.archiveSchedule)
    const [timeUnit, setTimeUnit] = useState(null);
    const [timeValue, setTimeValue] = useState(null);
    const [date, setDate] = useState("");
    const [isActive, setActive] = useState(false);
    const dispatch = useDispatch();

    useEffect(()=>{
        dispatch(getArchiveSchedule())
    },[dispatch])

    useEffect(()=>{
        if (!isEmpty(archiveSchedule)){
            if (archiveSchedule.success){
                setTimeUnit(archiveSchedule.data.time_unit)
                setTimeValue(archiveSchedule.data.unit_count)
                setActive(false)
            }
        }
    },[archiveSchedule, setTimeUnit, setTimeValue, setActive])

    useEffect(() => {
        if (isActive){
            if (!loading){
                destroyAlerts()
                savedAlert({
                    title: "Success",
                    description: "Schedule saved successfully.",
                })
                dispatch(saveLog({
                    title: "Saved older than archive schedule",
                    content: "Saved schedule archive Orders Older Than",
                    activity: "Saved schedule for archive orders older than",
                }))
            }
        }
    }, [loading, isActive]);

    const options = [
        { value: 'month',   label: 'Month'  },
        { value: 'year',    label: 'Year'   },
        { value: 'day',     label: 'Day'    },
        { value: 'hour',    label: 'Hour'   },
    ]

    const handleTimeUnitChange = (value) => {
        setTimeUnit(value);
    };

    const handleTimeValueChangeCount = (value) => {
        setTimeValue(value)
    };

    const optionsCount = Array.from({ length: 9 }, (_, index) => ({
        value: `${index + 1}`,
        label: index + 1
    }));

    const submitHandler = () =>{
        savingAlert({
            title: (<span className="ml-[10px] inline">Saving ...</span>),
            description: "Please wait! Schedule data is saving.",
        })
        if (!timeUnit && !timeValue){
            destroyAlerts()
            errorAlert({
                title: "Error",
                description: "Please select time unite and value!",
            })
            return
        }
        const getDate = calculateBackDate()
        setDate(getDate)

        dispatch(insertArchiveSchedule({
            "archive_time_unit" : timeUnit,
            "archive_unit_count": timeValue,
            "archive_schedule"  : getDate,
        }))

        setActive(true)
    }

    const calculateBackDate = () => {
        let backDate = dayjs();

        if (timeUnit === 'year') {
            backDate = backDate.subtract(timeValue, 'year');
        } else if (timeUnit === 'month') {
            backDate = backDate.subtract(timeValue, 'month');
        } else if (timeUnit === 'day') {
            backDate = backDate.subtract(timeValue, 'day');
        } else if (timeUnit === 'hour') {
            backDate = backDate.subtract(timeValue, 'hour');
        }

        return backDate.format('YYYY-MM-DD');
    };

    return (
        <div className="rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark mb-[15px]">
            <div className="border-b border-stroke px-6.5 py-4 dark:border-strokedark">
                <h3 className="font-medium text-black dark:text-white">
                    Archive Orders Older Than:
                </h3>
            </div>
            <form onSubmit={submitHandler} action="javaScript:void(0)">
                <div className="p-6.5">
                    <div className="mb-4.5">
                        <label className="mb-3 block text-sm font-medium text-black dark:text-white">Decide on a schedule for archiving.</label>
                        <Space className="mb-2 grid grid-cols-2" direction="vertical" size={2}>
                            <Select
                                placeholder="Select Time Unit"
                                onChange={handleTimeUnitChange}
                                options={options}
                                className="w-full"
                                value={timeUnit}
                            />
                            <Select
                                placeholder="Select Count"
                                onChange={handleTimeValueChangeCount}
                                options={optionsCount}
                                className="w-full"
                                value={timeValue === 0 ? "" : timeValue}
                            />
                        </Space>
                        <button className="flex w-full justify-center rounded bg-primary p-2 font-medium text-gray hover:bg-opacity-90">Save schedule</button>
                    </div>
                </div>
            </form>
        </div>
    );
};

export default ArchiveScheduleDate;