"use client"

import {motion} from "framer-motion";
import {useState, useEffect} from "react";

export default function PayrollOption({ pageName, items, setMethod }) {
    const [selectedMethod, setSelectedMethod] = useState(null);

    useEffect(() => {
        if (items && items.length > 0) {
            setSelectedMethod(items[0]);
            setMethod(items[0]); // انتخاب اولیه رو به صفحه پاس می‌ده
        }
    }, [items]);

    return (
        <div className="rounded-xl border-[1.5px] border-muted py-4 px-[14px] flex flex-col gap-4">
            <div className="font-extrabold text-xl text-secondary-main">
                {pageName}
            </div>

            <div className="w-full flex flex-wrap gap-10 md:grid md:grid-cols-2 relative">
                {items.map((item) => (
                    <button
                        key={item.id}
                        onClick={() => {
                            setMethod(item);
                            setSelectedMethod(item);
                        }}
                        className="relative py-4 px-2 rounded-lg text-[15px] font-medium md:py-4 md:text-[16px]"
                    >
                        {selectedMethod?.id === item.id && (
                            <motion.span
                                layoutId="bg"
                                transition={{ type: "spring", stiffness: 300, damping: 25 }}
                                className="absolute inset-0 bg-secondary-main rounded-lg"
                                initial={false}
                                animate={{ scale: [1, 1.05, 1] }}
                            />
                        )}
                        <motion.span
                            className="relative z-10"
                            animate={{
                                color: selectedMethod?.id === item.id ? "#fff" : "#0C0D0F",
                            }}
                            transition={{ duration: 0.2, ease: "easeInOut" }}
                        >
                            مبنای <span>{item.name}</span>
                        </motion.span>
                    </button>
                ))}
            </div>
        </div>
    );
}
