import React, {FC, useEffect, useState} from "react"
import useAxiosTools from "../../hooks/AxiosTools";
import {rainfall} from "../../types";
import {AxiosError} from "axios";
import Card from "../Card";

const LastFiveMesure: FC<LastFiveMesureProps> = ({loadedAt}) => {

    const {error, setError, axiosGet} = useAxiosTools()
    const [data, setData] = useState<rainfall[]>([])

    useEffect(() => {
        fetchData()
    }, [loadedAt])

    const fetchData = async () => {
        try {
            const res = await axiosGet('/api/rainfalls/last')
            setData(res.data)
        } catch (e) {
            if (e instanceof AxiosError) {
                setError(e.message)
            } else {
                console.error(e)
            }
        }
    }

    return <Card className="min-w-[200px] overflow-hidden self-start w-full lg:w-auto">
        <h1 className="text-center bg-blue-500 -mx-2 -mt-1 text-lg font-bold px-2 py-1">5 dernières mesures</h1>
        {error && <div>{error}</div>}
        <table className="w-full text-center">
            <tbody>
                {data.map(line => <tr key={line.id} className="">
                    <td>{(new Date(line.date)).toLocaleDateString()}</td>
                    <td className="text-right px-2">{line.value}</td>
                </tr>)}
            </tbody>
        </table>
    </Card>
}

export default LastFiveMesure

interface LastFiveMesureProps {
    loadedAt: Date,
}
