"use client"

import IntroContainer from "./_component/IntroContainer";
import Plans from "./_component/Plans";
import TablePlan from "@/app/Subscription/_component/TablePlan";
import QuestionBar from "@/app/Subscription/_component/questionBar";
import {useEffect, useState} from "react";
import LoadingOverlay from "@/components/ui/Loading/LoadingOverlay";

export default function Subscription() {



    const [planKind, setPlanKind] = useState("");

    const [apiData, setApiData] = useState([])

    const [currency, setCurrency] = useState("");
    const [planKinds, setPlanKinds] = useState([])
    const [plansCount, setPlansCount] = useState(0);
    const [plansData, setPlansData] = useState([]);


    const [loading, setLoading] = useState(true);

    const getApi = async () => {
        setLoading(true);
        try {
            const res = await fetch("https://www.vakilodoleh.ir/api/v1/plans");
            const data = await res.json();
            setApiData(data);

        } catch (error) {
            console.error("خطا در گرفتن اطلاعات:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        getApi();
    },[]);

    useEffect(() => {

        setPlanKinds(apiData.periods);
        setCurrency(apiData.currency);
        setPlansCount(apiData.plans_count);
        setPlansData(apiData.data);

        const firstKey = (Object.keys(apiData.data || {})[0]);
        if (firstKey) {
            setPlanKind(firstKey);
        }

    },[apiData]);



    return (
        <>
            {loading ? (
                <LoadingOverlay />
            ) : (
                <div>
                    <IntroContainer plans={planKinds} setPlanKind={setPlanKind} />

                    <div className="bg-box py-7 md:pt-0">
                        <Plans items={plansData} planKind={planKind} />
                    </div>


                    <div className="bg-white py-7">
                        <TablePlan planKinds={planKinds} />
                    </div>


                    <div className="bg-white py-7 mt-9">
                        <QuestionBar/>
                    </div>
                </div>
            )}
        </>

    )
}