"use client"
import Image from "next/image";
import line from "@/../public/icons/line.svg"
import {motion, AnimatePresence} from "framer-motion";
import {useEffect, useState} from "react";
import closwSquare from "../../../../public/icons/close-square.svg";
import checkSquare from "../../../../public/icons/checkPlans.svg";

export default function TablePlan({planKinds = []}) {
    const planItems = Object.entries(planKinds).map(([id, name]) => ({
        id,
        name,
    }));
    const [selectedPlanItem, setSelectedPlanItem] = useState(planItems[0]);

    useEffect(() => {
        setSelectedPlanItem(planItems[0]);
    }, [planKinds]);

    const [tableData, setTableData] = useState({monthly: [], yearly: []});

    const getApi = async () => {
        try {
            const res = await fetch("https://www.vakilodoleh.ir/api/v1/plans/features");
            const data = await res.json();
            setTableData(data);
        } catch (error) {
            console.error("خطا در گرفتن اطلاعات:", error);
        }
    };

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

    const currentPlans = selectedPlanItem ? tableData[selectedPlanItem.id] || [] : [];

    // Extract unique features from all plans
    const allFeatures = currentPlans.reduce((acc, plan) => {
        plan.features.forEach(feature => {
            if (!acc.find(f => f.name === feature.name)) {
                acc.push(feature);
            }
        });
        return acc;
    }, []);


    const renderFeatureValue = (feature) => {
        if (!feature) return "-";
        if (feature.type === "boolean") {
            return feature.enabled ?
                <Image width={25} height={25} src={checkSquare} alt="" className="mx-auto"/> :
                <Image src={closwSquare} alt="" width={25} height={25} className="mx-auto"/>;
        } else if (feature.type === "quota") {
            return feature.enabled ? (
                feature.limit === null ? "نامحدود" : `${feature.limit}`
            ) : <Image src={closwSquare} alt="" width={25} height={25} className="mx-auto"/>;
        }
        return "-";
    };

    const getFeatureByName = (plan, name) => plan?.features.find(f => f.name === name);

    return (
        <div className="flex flex-col items-center justify-center gap-4">
            <div className="flex flex-col gap-3">
                <p className="text-t2 font-black text-secondary-main md:text-t3 md:text-center">
                    مقایسه پلن‌های راوی حساب
                </p>
                <div className="w-full flex justify-center">
                    <Image src={line} alt={"line"} className="md:w-[90%]"/>
                </div>
            </div>

            <p className="text-body w-[30%] text-muted leading-10 text-center md:w-full md:px-6">
                پلن های مختلف اشتراک در راوی حساب این امکان را به شما میدهد تا بتوانید با توجه به نیازتان <b>بهترین انتخاب</b> را داشته باشید.
            </p>

            <div className="w-[90%] overflow-x-auto border-2 border-primary-main rounded-xl">
                <div>
                    <table className="table-auto w-full min-w-[800px] text-center">
                        <thead className="bg-white">
                        <tr className="border-b-2 border-black">
                            <th className="p-3 w-1/4 items-center">
                                <div className="relative flex p-1.5 w-fit justify-center items-center bg-secondary-main rounded-xl mx-auto">
                                    <span className="absolute -left-24 h-[2.5em] border-l border-muted"></span>
                                    {planItems.map((item) => (
                                        <button
                                            key={item.id}
                                            onClick={() => setSelectedPlanItem(item)}
                                            className="relative py-1 px-[18px] rounded-lg text-[11px] flex"
                                        >
                                            {selectedPlanItem?.id === item.id && (
                                                <motion.span
                                                    layoutId="table-bg"
                                                    transition={{ type: "spring", stiffness: 300, damping: 25 }}
                                                    className="absolute inset-0 bg-primary-main rounded-lg"
                                                    initial={false}
                                                    animate={{ scale: [1, 1.05, 1] }}
                                                />
                                            )}
                                            <motion.span
                                                className="relative z-10"
                                                animate={{
                                                    color: selectedPlanItem?.id === item.id ? "#0C0D0F" : "#fff",
                                                }}
                                                transition={{ duration: 0.3 }}
                                            >
                                                {item.name}
                                            </motion.span>
                                        </button>
                                    ))}
                                </div>
                            </th>

                            {currentPlans.map((plan) => (
                                <th key={plan.title} className="p-2 w-1/4">
                                    {plan.title}
                                </th>
                            ))}
                        </tr>
                        </thead>

                        <AnimatePresence mode="wait">
                            <motion.tbody
                                key={selectedPlanItem?.id}
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                                exit={{ opacity: 0, y: -20 }}
                                transition={{ duration: 0.4 }}
                            >
                                {allFeatures.map((feature, index) => (
                                    <motion.tr
                                        key={feature.name}
                                        initial={{ opacity: 0, y: 15 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        exit={{ opacity: 0, y: -15 }}
                                        transition={{ duration: 0.3, delay: index * 0.01 }}
                                        className={`${index % 2 === 0 ? `bg-box` : `bg-white`}`}
                                    >
                                        <td className="p-3 pr-8 text-right">{feature.name}</td>

                                        {currentPlans.map((plan) => (
                                            <td key={plan.title + feature.name} className="p-3">
                                                {renderFeatureValue(getFeatureByName(plan, feature.name))}
                                            </td>
                                        ))}
                                    </motion.tr>
                                ))}

                                <motion.tr
                                    initial={{ opacity: 0 }}
                                    animate={{ opacity: 1 }}
                                    exit={{ opacity: 0 }}
                                    transition={{ duration: 0.3 }}
                                >
                                    <td
                                        className="border-t-2 font-bold text-[18px] bg-primary-lighten border-primary-main py-1 px-6 text-right"
                                        colSpan={1 + currentPlans.length}
                                    >
                                        با اشتراک‌ راوی حساب برنده نهایی شمایید!
                                    </td>
                                </motion.tr>
                            </motion.tbody>
                        </AnimatePresence>
                    </table>

                </div>
            </div>
        </div>
    );
}
