"use client";

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

import FetchService from "./help/fetch-service";
import Donut from "./components/donut.jsx";
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.jsx";

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

    const handleFormSubmit = async (formData) => {
        setIsLoading(true);
        const data = await FetchService.fetchBarChartData(formData);
        setChartData(data);
        setIsLoading(false);
    };
    const loadInitialBarChartData = async () => {
        setIsLoading(true);
        try {
            const formData = {
                startDate: '2020-01-01',
                endDate: '2022-01-01',
                granularity: 'month'
            };
            const data = await FetchService.fetchBarChartData(formData);
            setChartData(data);
        } catch (error) {
            console.error('Error fetching bar chart data:', error);
        }
        setIsLoading(false);
    };

    useEffect(() => {
        (async () => {
            loadInitialBarChartData();
            try {
                const response = await FetchService.getTimesSeries();
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                const data = await response.json();
                setLineData(data);
            } catch (error) {
                console.error('Error fetching time series data:', error);
            }
            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 data={lineData} />
                </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>
        </>
    );
}

