import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";

import Breadcrumbs from "../../../../../commonComponents/breadcrumbs/Breadcrumbs";

import BasicInfo from "./components/BasicInfo";
import CategorySelect from "./components/CategorySelect";
import DescriptionEditor from "./components/DescriptionEditor";
import PricingAndMedia from "./components/PricingAndMedia";
import Inventory from "./components/Inventory";
import ProductOptions from "./components/ProductOptions";
import Variants from "./components/Variants";
import Modifiers from "./components/Modifiers";
import AdditionalInfoSections from "./components/AdditionalInFoSection";

export default function NewPhysicalProduct() {
    const navigate = useNavigate();
    const location = useLocation();
    const productFromState = location.state?.product || null;

    /* ------------------------ STATE ------------------------ */
    const [title, setTitle] = useState("");
    const [ribbon, setRibbon] = useState("");
    const [brand, setBrand] = useState("");
    const [description, setDescription] = useState("");
    const [selectedCategory, setSelectedCategory] = useState("");
    const [price, setPrice] = useState("");
    const [strikethroughPrice, setStrikethroughPrice] = useState("");
    const [cost, setCost] = useState("");
    const [profit, setProfit] = useState("--");
    const [margin, setMargin] = useState("--");
    const [showPricePerUnit, setShowPricePerUnit] = useState(false);
    const [baseUnitValue, setBaseUnitValue] = useState(1);
    const [baseUnitLabel, setBaseUnitLabel] = useState("piece");
    const [totalUnitsInProduct, setTotalUnitsInProduct] = useState(1);
    const [media, setMedia] = useState([]);
    const [options, setOptions] = useState([]);
    const [trackInventory, setTrackInventory] = useState(false);
    const [quantity, setQuantity] = useState("");
    const [stockStatus, setStockStatus] = useState("in_stock");
    const [sku, setSku] = useState("");
    const [barcode, setBarcode] = useState("");
    const [allowPreorder, setAllowPreorder] = useState(false);
    const [limitPreorder, setLimitPreorder] = useState(false);
    const [preorderLimit, setPreorderLimit] = useState("");
    const [preorderMessage, setPreorderMessage] = useState("");
    const [variants, setVariants] = useState([]);
    const [modifiers, setModifiers] = useState([]);
    const [infoSections, setInfoSections] = useState([]);
    const [reusableInfoLibrary, setReusableInfoLibrary] = useState([]);
    const [rating, setRating] = useState("");
    const [reviewsCount, setReviewsCount] = useState("");


    const API_URL = import.meta.env.VITE_API_URL;

    /* ------------------- LOAD REUSABLE INFO LIBRARY ------------------- */
    useEffect(() => {
        const loadReusableInfo = async () => {
            try {
                const res = await axios.get(`${API_URL}/api/product/infosection-library`);
                setReusableInfoLibrary(res.data);
            } catch (err) {
                console.log("Failed loading reusable info", err);
            }
        };
        loadReusableInfo();
    }, [API_URL]);

    /* ------------------- LOAD PRODUCT IN EDIT MODE ------------------- */
    useEffect(() => {
        const id = productFromState?._id || productFromState?.id;
        if (!id) return;

        const loadProduct = async () => {
            try {
                const res = await axios.get(`${API_URL}/api/product/allproduct/${id}`);
                const p = res.data;

                setTitle(p.name || "");
                setRibbon(p.ribbon || "");
                setBrand(p.brand || "");
                setDescription(p.description || "");

                // ✅ KEEP ONLY THIS LINE. FIXED.
                setSelectedCategory(
                    typeof p.category === "string"
                        ? p.category
                        : p.category?.$oid || p.category?._id || p.category?.id || ""
                );

                setPrice(p.price || "");
                setStrikethroughPrice(p.strikethroughPrice || "");
                setCost(p.costOfGoods || "");

                setProfit(p.profit ? `₹${p.profit}` : "--");
                setMargin(p.margin ? `${p.margin}%` : "--");

                setTrackInventory(p.trackInventory);
                setQuantity(p.stockQuantity || "");
                setStockStatus(p.status || "in_stock");

                setSku(p.sku || "");
                setBarcode(p.barcode || "");

                setOptions(p.options || []);
                setVariants(p.variants || []);
                setModifiers(p.modifiers || []);
                setInfoSections(p.infoSections || []);

                setMedia(
                    p.media?.map((m) => ({
                        id: m._id || Date.now(),
                        url: `${API_URL}${m.url}`,
                        preview: `${API_URL}${m.url}`,
                        type: m.type,
                    })) || []
                );
            } catch (err) {
                console.error(err);
                toast.error("Failed to load product");
            }
        };

        loadProduct();
    }, [productFromState, API_URL]);

    /* ------------------- PROFIT & MARGIN CALC ------------------- */
    useEffect(() => {
        if (!price || !cost) {
            setProfit("--");
            setMargin("--");
            return;
        }

        const p = Number(price);
        const c = Number(cost);
        const pr = p - c;
        const mg = p === 0 ? 0 : ((pr / p) * 100).toFixed(2);

        setProfit(`₹${pr.toFixed(2)}`);
        setMargin(`${mg}%`);
    }, [price, cost]);

    /* ------------------- SAVE PRODUCT ------------------- */
    /* ------------------- SAVE PRODUCT ------------------- */
    const handleSaveProduct = async () => {
        try {
            // REQUIRED FIELDS (backend validation)
            if (!title.trim()) return toast.error("Product name is required");
            if (!brand.trim()) return toast.error("Brand is required");
            if (!description.trim()) return toast.error("Description is required");
            if (!selectedCategory) return toast.error("Category is required");
            if (!price) return toast.error("Price is required");
            if (media.length === 0) return toast.error("Upload at least one image");

            // IMPORTANT: backend requires only these fields
            const payload = {
                name: title,
                ribbon,
                brand,
                description,
                category: selectedCategory, // MUST BE ObjectId
                price: Number(price),
                strikethroughPrice: Number(strikethroughPrice) || 0,
                costOfGoods: Number(cost) || 0,
                profit: profit === "--" ? 0 : Number(profit.replace("₹", "")),
                margin: margin === "--" ? 0 : Number(margin.replace("%", "")),
                trackInventory,
                stockQuantity: Number(quantity),
                status: stockStatus,
                sku,
                barcode,
                options,
                variants,
                modifiers,
                infoSections,
                rating: Number(rating) || 0,
                reviewsCount: Number(reviewsCount) || 0,
            };

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

            // only new uploaded files go through multer
            media.filter(m => m.file).forEach(m => {
                fd.append("media", m.file);
            });

            const id = productFromState?._id || productFromState?.id;

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

            navigate("/admin/products");

        } catch (err) {
            console.log(err.response?.data);
            toast.error(err.response?.data?.message || "Failed to save product");
        }
    };


    /* ------------------- UI ------------------- */
    return (
        <div className="min-h-screen bg-gray-50 flex flex-col">
            <div className="p-4 sm:p-6 max-w-6xl mx-auto w-full">
                <Breadcrumbs
                    paths={[
                        { label: "Products", to: "/admin/products" },
                        { label: productFromState ? "Edit Product" : "New Product" },
                    ]}
                />
            </div>

            <div className="sticky top-16 z-40 bg-white border-b shadow-sm">
                <div className="flex items-center justify-between px-6 py-4">
                    <h1 className="text-2xl font-semibold">
                        {productFromState ? "Edit Product" : "New Product"}
                    </h1>

                    <div className="flex gap-3">
                        <button
                            onClick={() => navigate("/admin/products")}
                            className="px-4 py-2 border rounded-lg"
                        >
                            Cancel
                        </button>

                        <button
                            onClick={handleSaveProduct}
                            className="px-4 py-2 bg-orange-600 text-white rounded-lg"
                        >
                            Save
                        </button>
                    </div>
                </div>
            </div>

            <main className="flex-1 overflow-y-auto">
                <div className="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-12 gap-6 p-6">
                    <div className="lg:col-span-8 space-y-6">
                        <BasicInfo
                            title={title}
                            setTitle={setTitle}
                            ribbon={ribbon}
                            setRibbon={setRibbon}
                            brand={brand}
                            setBrand={setBrand}
                            rating={rating}
                            setRating={setRating}
                            reviewsCount={reviewsCount}
                            setReviewsCount={setReviewsCount}
                        />

                        <DescriptionEditor
                            description={description}
                            setDescription={setDescription}
                        />

                        <PricingAndMedia
                            price={price}
                            setPrice={setPrice}
                            strikethroughPrice={strikethroughPrice}
                            setStrikethroughPrice={setStrikethroughPrice}
                            cost={cost}
                            setCost={setCost}
                            profit={profit}
                            margin={margin}
                            media={media}
                            setMedia={setMedia}
                            showPricePerUnit={showPricePerUnit}
                            setShowPricePerUnit={setShowPricePerUnit}
                            baseUnitValue={baseUnitValue}
                            setBaseUnitValue={setBaseUnitValue}
                            baseUnitLabel={baseUnitLabel}
                            setBaseUnitLabel={setBaseUnitLabel}
                            totalUnitsInProduct={totalUnitsInProduct}
                            setTotalUnitsInProduct={setTotalUnitsInProduct}
                        />

                        <Inventory
                            trackInventory={trackInventory}
                            setTrackInventory={setTrackInventory}
                            quantity={quantity}
                            setQuantity={setQuantity}
                            stockStatus={stockStatus}
                            setStockStatus={setStockStatus}
                            sku={sku}
                            setSku={setSku}
                            barcode={barcode}
                            setBarcode={setBarcode}
                            allowPreorder={allowPreorder}
                            setAllowPreorder={setAllowPreorder}
                            limitPreorder={limitPreorder}
                            setLimitPreorder={setLimitPreorder}
                            preorderLimit={preorderLimit}
                            setPreorderLimit={setPreorderLimit}
                            preorderMessage={preorderMessage}
                            setPreorderMessage={setPreorderMessage}
                        />

                        <ProductOptions
                            options={options}
                            setOptions={setOptions}
                            variants={variants}
                            setVariants={setVariants}
                        />

                        <Variants
                            options={options}
                            variants={variants}
                            setVariants={setVariants}
                        />

                        <Modifiers modifiers={modifiers} setModifiers={setModifiers} />

                        <AdditionalInfoSections
                            infoSections={infoSections}
                            setInfoSections={setInfoSections}
                            reusableInfoLibrary={reusableInfoLibrary}
                        />
                    </div>

                    <div className="lg:col-span-4">
                        <CategorySelect
                            selectedCategory={selectedCategory}
                            setSelectedCategory={setSelectedCategory}
                        />
                    </div>
                </div>
            </main>
        </div>
    );
}
