"use client";

import React, {useEffect, useState} from "react";
import constants 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 Timeseries from "./components/timeseries/timeseries.jsx";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner } from "@fortawesome/free-solid-svg-icons";

export default function Page() {
    const [donutValues, setDonutValues] = useState([]);
    const [chartData, setChartData] = useState([]);
    const [lineData, setLineData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);

    const handleFormSubmit = async (formData) => {
        setIsLoading(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);
        setIsLoading(false);
    };

    const loadInitialBarChartData = async () => {
        setIsLoading(true);
        try {
            const formData = {
                startDate: `${constants.initialBarChartFormData.startDate}`,
                endDate: `${constants.initialBarChartFormData.endDate}`,
                granularity: `${constants.initialBarChartFormData.granularity}`
            };
            const response = await FetchService.fetchBarChartData(formData);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            setChartData(data);
        } catch (error) {
            console.error('Error fetching bar chart data:', error);
        }
        setIsLoading(false);
    };

    useEffect(() => {
        (async () => {
            // bar chart
            loadInitialBarChartData();

            // time series
            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);
            }

            // donut
            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>
                    <Timeseries data={lineData} />
                </div>
                <div className="card">
                    <h3>Nombre des ventes par période</h3>
                    <DataForm onSubmit={handleFormSubmit}/>
                    {isLoading? (
                        <FontAwesomeIcon className="spinner" icon={faSpinner} spin size="3x" />
                    ) : (
                        <BarChart data={chartData}/>
                    )}
                </div>
                <div className="card">
                    <h3>Répartition des ventes par régions</h3>
                    <DateInput/>
                    <Donut data={donutValues}/>
                </div>
            </div>
        </>
    );
}

