
import axios from "axios";
import  {toast}  from "sonner";
import { useNavigate } from "react-router-dom";

export default function RightSidebar({
    handleSaveProduct, // if you still want to optionally pass this as prop
    selectedCategory,
    setSelectedCategory,
    sku,
    setSku,
    ribbon,
    setRibbon,
    children, // CategorySelect
    title,
    price,
    strikethroughPrice,
    cost,
    profit,
    margin,
    showPricePerUnit,
    baseUnitValue,
    baseUnitLabel,
    totalUnitsInProduct,
    trackInventory,
    quantity,
    stockStatus,
    barcode,
    brand,
    description,
    options,
    variants,
    modifiers,
    infoSections,
    media,
    productId,
    API_URL,
}) {
    const navigate = useNavigate();

    const handleSave = async () => {
        try {
            if (!title?.trim()) return toast.error("Product name is required");
            if (!selectedCategory) return toast.error("Select a category");
            if (!price) return toast.error("Price is required");
            if (!media || media.length === 0) return toast.error("Upload at least one image");

            const payload = {
                name: title,
                ribbon,
                brand,
                description,
                category: selectedCategory,
                price: Number(price),
                strikethroughPrice: Number(strikethroughPrice) || 0,
                costOfGoods: Number(cost) || 0,
                profit: profit === "--" ? 0 : Number(profit.replace("₹", "")),
                margin: margin === "--" ? 0 : Number(margin.replace("%", "")),
                showPricePerUnit,
                baseUnitValue,
                baseUnitLabel,
                totalUnitsInProduct,
                pricePerUnit: Number(price),
                trackInventory,
                stockQuantity: Number(quantity),
                status: stockStatus,
                sku,
                barcode,
                options,
                variants,
                modifiers,
                infoSections,
            };

            const existingMedia = media
                .filter((m) => !m.file)
                .map((m) => ({
                    url: m.url,
                    type: m.type,
                    _id: m.id,
                }));

            const fd = new FormData();
            fd.append("data", JSON.stringify(payload));
            fd.append("existingMedia", JSON.stringify(existingMedia));

            media
                .filter((m) => m.file)
                .forEach((m) => {
                    fd.append("media", m.file);
                });

            if (productId) {
                await axios.put(`${API_URL}/api/product/editproduct/${productId}`, fd);
                toast.success("Product updated");
            } else {
                await axios.post(`${API_URL}/api/product/createproduct`, fd);
                toast.success("Product created");
            }

            navigate("/admin/products");
        } catch (err) {
            console.error(err);
            toast.error("Failed to save product");
        }
    };

    return (
        <div className="space-y-6">
            <section className="bg-white rounded-xl shadow-sm p-5">
                <h3 className="font-semibold mb-3">Category</h3>
                {children}
            </section>

            <section className="bg-white rounded-xl shadow-sm p-5 space-y-3">
                <div>
                    <label className="text-sm font-medium">SKU</label>
                    <input
                        type="text"
                        value={sku}
                        onChange={(e) => setSku(e.target.value)}
                        className="w-full border rounded-lg px-3 py-2 mt-1"
                    />
                </div>

                <div>
                    <label className="text-sm font-medium">Ribbon</label>
                    <input
                        type="text"
                        value={ribbon}
                        onChange={(e) => setRibbon(e.target.value)}
                        className="w-full border rounded-lg px-3 py-2 mt-1"
                        placeholder="New, Sale, Trending"
                    />
                </div>

                <button
                    onClick={handleSaveProduct || handleSave}
                    className="w-full bg-orange-600 hover:bg-orange-500 text-white py-2 rounded-lg"
                >
                    Save Product
                </button>
            </section>
        </div>
    );
}
