import React, { useEffect, useState } from 'react';
import {useSelector, useDispatch } from 'react-redux'
import Spinner from '../../components/Spinner'
import ProgressBar from 'react-bootstrap/ProgressBar';
import { reset, getpurchasesbydate, deletepurchase, getCO2bydate} from '../../features/purchases/purchaseSlice'
import {LinePurchase} from './LinePurchase'
import { useTranslation } from 'react-i18next';
import { startOfWeek, endOfWeek } from 'date-fns';
import { enGB, fr } from 'date-fns/locale';
import DatePicker, { registerLocale } from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";

export const  HomePurchase = () => {
    const { isLoading, purchases, CO2Emissions } = useSelector((state) => state.purchase)
    const [startDate, setStartDate] = useState(startOfWeek(new Date(), { weekStartsOn: 1 }));
    const [endDate, setEndDate] = useState(endOfWeek(new Date(), { weekStartsOn: 1 }));
    const [purchasesUser, setPurchasesUser] = useState([]);
    const [CO2EmissionsPurcentage, setCO2EmissionsPurcentage] = useState(0.0);
    const { t } = useTranslation(["Home"]);
    const rangeSeparator = " " + t("dateSeparator") + " ";
    registerLocale('en-GB', enGB);

    const dispatch = useDispatch()

    useEffect(() => {
        setPurchasesUser(purchases);
        setCO2EmissionsPurcentage((endDate === undefined) ? 0 : (CO2Emissions / (2500 / 365 * (endDate?.getDate() - startDate.getDate() + 1)) * 100));
    }, [purchases, CO2Emissions]);

    useEffect(() => {
        if (endDate) {
            changeDate();
        }
    }, [startDate, endDate])

    const onChangeDates = (dates) => {
        const [start, end] = dates;
        setStartDate(start);
        setEndDate(end);
    };

    function changeDate() {
        dispatch(reset())
        dispatch(getpurchasesbydate({ 
            startDate: startDate.toLocaleDateString("es-CL"), 
            endDate: endDate?.toLocaleDateString("es-CL")
        }));
        dispatch(getCO2bydate({ 
            startDate: startDate.toLocaleDateString("es-CL"), 
            endDate: endDate?.toLocaleDateString("es-CL")
        }));
    }

    const deletePurchase = (p) => {
        dispatch(reset());
        dispatch(deletepurchase(p)).then(
            changeDate()
        );
    }

    if (isLoading)
        return <Spinner />
    else
        return (
            <>
                <div className='center'>
                    {t("labelCost")}
                    <DatePicker
                        dateFormat="dd/MM/yyyy"
                        locale="fr"
                        selected={startDate}
                        onChange={onChangeDates}
                        startDate={startDate}
                        endDate={endDate}
                        selectsRange
                        rangeSeparator={rangeSeparator}
                    />
                </div>
                <div className='mbottom-20'>
                    <ProgressBar now={CO2EmissionsPurcentage} label={`${CO2EmissionsPurcentage.toFixed(2)}%`} />
                </div>
                <div className="form-group width-100">
                    
                </div>
                <div className='flex'>
                    <div className='form-group width-30'>{t("date")}</div>
                    <div className='form-group width-30'>{t("CO2Cost")}</div>
                    <div className='form-group width-30'>{t("WaterCost")}</div>
                </div>
                {
                    purchasesUser.map((purchaseUser, index) => {
                        return (
                            <LinePurchase key={index} purchaseUser={purchaseUser} onChange={(p) => deletePurchase(p)} />
                        )                    
                    })
                }
            </>
        );
}

export default HomePurchase