"use client";

import React, {useEffect, useState} from "react";
import config from '../config.js';

import FetchService from "./help/fetch-service";
import Donut from "./components/donut.tsx";
import DateInput from "./components/date-input";
import DataForm from "./components/bar-chart/form";
import BarChart from "./components/bar-chart/chart";
import Line_Chart from "./components/line_chart.tsx";

export default function Page() {
    const [donutValues, setDonutValues] = useState([]);
    const [chartData, setChartData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const Loader = () => <div>Loading...</div>;

    const handleFormSubmit = async (formData) => {
        setIsLoading(true);
        const url = `${config.apiUrl}/bar-chart/${formData.startDate}/${formData.endDate}/${formData.granularity}?page=1`;
        const response = await fetch(url);    const data = await response.json();
        console.log(data);
        setChartData(data);
        setIsLoading(false);
    };

    useEffect(() => {
        (async () => {
            const data = await FetchService.getDonutContent();
            const formattedData = data.map((x) => ({
                id: x.region,
                count: x.occurences
            }));
            setDonutValues(formattedData);
        })();
    }, []);

    return (
        <>
            <div className="card-container">
                <div className="card">
                    <h3>L’évolution du prix de vente moyen du mètre carré </h3>
                    <Line_Chart/>
                </div>
                <div className="card">
                    <h3>Nombre des ventes par période</h3>
                    {isLoading && <Loader />}
                    <DataForm onSubmit={handleFormSubmit} />
                    <BarChart data={chartData} />
                </div>
                <div className="card">
                    <h3>Répartition des ventes par régions</h3>
                    <DateInput/>
                    <Donut data={donutValues}/>
                </div>
            </div>
        </>
    );
}
