"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 [isLoadingBar, setIsLoadingBar] = useState(false);
    const [isLoadingDonut, setIsLoadingDonut] = useState(false);
    const [isLoadingTimeseries, setIsLoadingTimesseries] = useState(false);

    const handleFormSubmit = async (formData) => {
        setIsLoadingBar(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);
        setIsLoadingBar(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(() => {
        (async () => {
            // bar chart
            const formData = {
                startDate: `${constants.initialBarChartFormData.startDate}`,
                endDate: `${constants.initialBarChartFormData.endDate}`,
                granularity: `${constants.initialBarChartFormData.granularity}`
            };
            await handleFormSubmit(formData);

            // time series
            try {
                setIsLoadingTimesseries(true);
                const response = await FetchService.getTimesSeries();
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                const data = await response.json();
                setTimeseries(data);
                setIsLoadingTimesseries(false);
            } catch (error) {
                console.error('Error fetching time series data:', error);
            }

            // donut
            await handleYearSubmit(2020);

        })();
    }, []);

    return (
        <>
            <div className="card-container">
                <div className="card">
                    <h3>L’évolution du prix de vente moyen du mètre carré </h3>
                    {isLoadingTimeseries? (
                        <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}/>
                    {isLoadingBar? (
                        <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}/>
                    {isLoadingDonut? (
                        <FontAwesomeIcon className="spinner" icon={faSpinner} spin size="3x" />
                    ):(
                        <div className="donut-container">
                            <Donut data={donutValues} />
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

