import React, {useEffect, useState} from "react"
import PageLayout from "../../components/PageLayout"
import LastFiveMesure from "../../components/rainfall/LastFiveMesure"
import AddRainfall from "../../components/rainfall/AddRainfall"
import useAxiosTools from "../../hooks/AxiosTools"
import {rainfallGraphData} from "../../types"
import Field from "../../components/Field"
import useDimension from "../../hooks/DimensionHook"
import RainFallEcharts from "../../components/rainfall/RainFallEcharts"

const RainfallGraph = () => {

    const [loadedAt, reload] = useState(new Date)
    const [graphData, setGraphData] = useState<rainfallGraphData[]>([])
    const [graphDetails, setGraphDetails] = useState({
        start_date: (new Date((new Date()).setMonth((new Date).getMonth() - 1))).toSQLDate(),
        end_date: (new Date()).toSQLDate(),
        period: 'day',
    })
    const {loading, setLoading, errorCatch, errorLabel, axiosGet} = useAxiosTools()
    const {targetRef, dimensions} = useDimension()

    useEffect(() => {
        setLoading(true)
        fetchGraphData()
    }, [loadedAt, graphDetails])

    const fetchGraphData = async () => {
        try {
            const params = `start=${graphDetails.start_date}&end=${graphDetails.end_date}&period=${graphDetails.period}`
            const res = await axiosGet(`/api/rainfalls/graph?${params}`)
            setGraphData(res.data)
        } catch (error) {
            errorCatch(error)
        } finally {
            setLoading(false)
        }
    }

    return <PageLayout>
        {errorLabel()}
        <div className="mx-5 mb-2 flex items-center justify-between">
            <form className="flex flex-wrap gap-2">
                <Field name="start_date"
                       type="date"
                       value={graphDetails.start_date}
                       onChange={e => setGraphDetails({
                           ...graphDetails,
                           start_date: (new Date(e.target.value)).toSQLDate()
                       })}/>
                <Field name="start_date"
                       type="date"
                       value={graphDetails.end_date}
                       onChange={e => setGraphDetails({
                           ...graphDetails,
                           end_date: (new Date(e.target.value)).toSQLDate()
                       })}/>
                <div className="form-control">
                    <select className={` mt-2 w-full rounded dark:bg-gray-700`}
                            value={graphDetails.period}
                            onChange={e => setGraphDetails({...graphDetails, period: e.target.value})}>
                        <option value="day">Jour</option>
                        {/*    <option value="week">Semaine</option>*/}
                        <option value="month">Mois</option>
                        <option value="year">Année</option>
                    </select>
                </div>
            </form>
            <div>Total : <strong>{graphData.reduce((result, item) => result += item.value, 0)}</strong> mm</div>
        </div>

        <div ref={targetRef} className="mb-20 min-h-96">
            <RainFallEcharts width={dimensions.width}
                             height={500}
                             data={graphData}
                             loading={loading}/>
        </div>

        <div className="flex flex-wrap justify-between gap-2">
            <AddRainfall reload={reload}/>
            <LastFiveMesure loadedAt={loadedAt}/>
        </div>
    </PageLayout>
}

export default RainfallGraph
