"use client";

import React, {useEffect, useState} from "react";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner } from "@fortawesome/free-solid-svg-icons";

import constants from '../config.js';
import FetchService from "./help/fetch-service";

import Donut from "./components/donut-chart/donut.jsx";
import YearInput from "./components/donut-chart/year-input.jsx";
import DataForm from "./components/bar-chart/form";
import BarChart from "./components/bar-chart/chart";
import Timeseries from "./components/timeseries/timeseries.jsx";


export default function Page() {
    const [donutValues, setDonutValues] = useState([]);
    const [chartData, setChartData] = useState([]);
    const [timeseries, setTimeseries] = useState([]);

    const [isLoading, setIsLoading] = useState(false);
    const [isLoadingDonut, setIsLoadingDonut] = useState(false);
    const [isLoadingBarChart, setIsLoadingBarChart] = useState(false);

    const handleFormSubmit = async (formData) => {
        setIsLoadingBarChart(true);
        const response = await FetchService.fetchBarChartData(formData);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setChartData(data);
        setIsLoadingBarChart(false);
    };

    const handleYearSubmit = async (year) => {
        setIsLoadingDonut(true);
        const response = await FetchService.getDonutContent(year);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setDonutValues(data);
        setIsLoadingDonut(false);
    }

    useEffect(() => {
        const fetchData = async () => {
            try {
                setIsLoading(true);

                const formData = {
                    startDate: constants.initialBarChartFormData.startDate,
                    endDate: constants.initialBarChartFormData.endDate,
                    granularity: constants.initialBarChartFormData.granularity,
                }

                const year = constants.initialDonutChartYear.selectedYear;

                const [timeseriesResponse, barChartResponse, donutChartResponse] = await Promise.all([
                    FetchService.getTimesSeries(),
                    FetchService.fetchBarChartData(formData),
                    FetchService.getDonutContent(year),
                ]);


                if (!timeseriesResponse.ok || !barChartResponse.ok || !donutChartResponse.ok) {
                    throw new Error(`HTTP error!`);
                }

                setTimeseries(await timeseriesResponse.json());
                setChartData(await barChartResponse.json());
                setDonutValues(await donutChartResponse.json());

                setIsLoading(false);
            } catch (error) {
                console.error('Error fetching data:', error);
            }
        };

        fetchData();
    }, []);

    return (
        <>
            <div className="card-container">
                <div className="card">
                    <h3>L’évolution du prix de vente moyen du mètre carré </h3>
                    {isLoading? (
                        <FontAwesomeIcon className="spinner" icon={faSpinner} spin size="3x" />
                    ): (
                        <Timeseries data={timeseries} />
                    )}
                </div>
                <div className="card">
                    <h3>Nombre des ventes par période</h3>
                    <DataForm onSubmit={handleFormSubmit}/>
                    {( isLoading || isLoadingBarChart )? (
                        <FontAwesomeIcon className="spinner" icon={faSpinner} spin size="3x" />
                    ) : (
                        <BarChart data={chartData}/>
                    )}
                </div>
                <div className="card donut-card">
                    <h3>Répartition des ventes par régions</h3>
                    <YearInput onDateChange={handleYearSubmit}/>
                    {(isLoading || isLoadingDonut)? (
                        <FontAwesomeIcon className="spinner" icon={faSpinner} spin size="3x" />
                    ):(
                        <div className="donut-container">
                            <Donut data={donutValues} />
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

