import { useRef, useMemo } from "react";
import { UploadCloud, X, Info } from "lucide-react";
import { ReactSortable } from "react-sortablejs";


export default function PricingAndMedia({
    price,
    setPrice,
    strikethroughPrice,
    setStrikethroughPrice,
    cost,
    setCost,
    profit,
    margin,

    //  Price per unit props
    showPricePerUnit,
    setShowPricePerUnit,
    baseUnitValue,
    setBaseUnitValue,
    baseUnitLabel,
    setBaseUnitLabel,
    totalUnitsInProduct,
    setTotalUnitsInProduct,

    // ✅ Media
    media,
    setMedia,
}) {
    const fileInputRef = useRef(null);

    /* ---------------- Compute Price Per Unit ---------------- */
    const pricePerUnit = useMemo(() => {
        if (!showPricePerUnit || !price || !baseUnitValue) return null;
        const p = parseFloat(price);
        const unit = parseFloat(baseUnitValue);
        if (isNaN(p) || isNaN(unit) || unit === 0) return null;

        return `₹${(p / unit).toFixed(2)} / ${unit} ${baseUnitLabel}`;
    }, [showPricePerUnit, price, baseUnitValue, baseUnitLabel]);

    /* ---------------- Upload Handler ---------------- */
    const handleUpload = (e) => {
        const files = Array.from(e.target.files);

        if (media.length + files.length > 15) {
            alert("You can upload a maximum of 15 files.");
            return;
        }

        const newMedia = files.map((file) => ({
            id: Date.now() + Math.random(),
            file,
            preview: URL.createObjectURL(file),
            type: file.type,
        }));

        setMedia((prev) => [...prev, ...newMedia]);
    };

    /* ---------------- Remove Media ---------------- */
    const removeItem = (id) => {
        setMedia((prev) => prev.filter((m) => m.id !== id));
    };

    /* ---------------- Toggle Component ---------------- */
    const Toggle = ({ enabled, onToggle }) => (
        <div
            onClick={onToggle}
            className={`w-12 h-6 rounded-full cursor-pointer transition-all flex items-center 
                ${enabled ? "bg-orange-500" : "bg-gray-300"}`}
        >
            <div
                className={`h-5 w-5 bg-white rounded-full shadow-md transform transition-all ml-1
                    ${enabled ? "translate-x-6" : ""}`}
            ></div>
        </div>
    );

    return (
        <section className="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h2 className="text-xl font-semibold mb-2">Pricing</h2>
            <p className="text-gray-500 mb-4">
                Set up the pricing details of this product.
            </p>

            <hr className="mb-4" />

            {/* ✅ Pricing Inputs */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label className="text-sm font-medium flex items-center gap-1">
                        Price *
                        <Info size={16} className="text-orange-500" />
                    </label>

                    <input
                        type="number"
                        className="w-full border rounded-lg px-3 py-2 mt-1"
                        placeholder="₹ 100"
                        value={price}
                        onChange={(e) => setPrice(e.target.value)}
                    />
                </div>

                <div>
                    <label className="text-sm font-medium flex items-center gap-1">
                        Strikethrough Price
                        <Info size={16} className="text-orange-500" />
                    </label>

                    <input
                        type="number"
                        className="w-full border rounded-lg px-3 py-2 mt-1"
                        placeholder="₹ 120"
                        value={strikethroughPrice}
                        onChange={(e) => setStrikethroughPrice(e.target.value)}
                    />
                </div>
            </div>

            {/* ✅ Cost + Profit + Margin */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div>
                    <label className="text-sm font-medium flex items-center gap-1">
                        Cost of goods
                        <Info size={16} className="text-orange-500" />
                    </label>

                    <input
                        type="number"
                        className="w-full border rounded-lg px-3 py-2 mt-1"
                        placeholder="₹ 50"
                        value={cost}
                        onChange={(e) => setCost(e.target.value)}
                    />
                </div>

                <div>
                    <label className="text-sm font-medium flex items-center gap-1">
                        Profit
                        <Info size={16} className="text-orange-500" />
                    </label>
                    <div className="w-full border bg-gray-50 rounded-lg px-3 py-2 mt-1">
                        {profit}
                    </div>
                </div>

                <div>
                    <label className="text-sm font-medium flex items-center gap-1">
                        Margin
                        <Info size={16} className="text-orange-500" />
                    </label>
                    <div className="w-full border bg-gray-50 rounded-lg px-3 py-2 mt-1">
                        {margin}
                    </div>
                </div>
            </div>

            {/* ✅ ---- PRICE PER UNIT SECTION ---- */}
            <div className="py-3">
                <div className="flex items-center gap-3 mt-2">
                    <Toggle
                        enabled={showPricePerUnit}
                        onToggle={() => setShowPricePerUnit(!showPricePerUnit)}
                    />

                    <span className="font-medium flex items-center gap-1">
                        Show price per unit
                        <Info size={16} className="text-orange-500" />
                    </span>
                </div>

                {showPricePerUnit && (
                    <div className="mt-5 grid grid-cols-1 md:grid-cols-2 gap-6">

                        {/* ✅ Base unit */}
                        <div>
                            <label className="text-sm font-medium flex items-center gap-1">
                                Base unit *
                                <Info size={16} className="text-orange-500" />
                            </label>

                            <div className="flex gap-2 mt-1">
                                <input
                                    type="number"
                                    className="border rounded-lg px-3 py-2 w-32"
                                    placeholder="1"
                                    value={baseUnitValue}
                                    onChange={(e) => setBaseUnitValue(e.target.value)}
                                />

                                <select
                                    value={baseUnitLabel}
                                    onChange={(e) => setBaseUnitLabel(e.target.value)}
                                    className="border rounded-lg px-3 py-2 w-24 bg-white"
                                >
                                    <option value="kg">kg</option>
                                    <option value="g">g</option>
                                    <option value="ml">ml</option>
                                    <option value="l">l</option>
                                    <option value="piece">piece</option>
                                </select>
                            </div>
                        </div>

                        {/* ✅ Total units in product */}
                        <div>
                            <label className="text-sm font-medium flex items-center gap-1">
                                Total units in product *
                                <Info size={16} className="text-orange-500" />
                            </label>

                            <div className="flex gap-2 mt-1">
                                <input
                                    type="number"
                                    className="border rounded-lg px-3 py-2 w-32"
                                    placeholder="1000"
                                    value={totalUnitsInProduct}
                                    onChange={(e) => setTotalUnitsInProduct(e.target.value)}
                                />

                                <select
                                    className="border rounded-lg px-3 py-2 w-24 bg-white"
                                    defaultValue="g"
                                >
                                    <option value="g">g</option>
                                    <option value="kg">kg</option>
                                    <option value="ml">ml</option>
                                    <option value="l">l</option>
                                </select>
                            </div>
                        </div>
                    </div>
                )}

                {/* ✅ Price Per Unit Output */}
                {showPricePerUnit && pricePerUnit && (
                    <div className="mt-5">
                        <label className="text-sm font-medium flex items-center gap-1">
                            Price per unit
                            <Info size={16} className="text-orange-500" />
                        </label>

                        <p className="text-lg font-semibold mt-1">
                            {pricePerUnit}
                        </p>
                    </div>
                )}
            </div>

            {/* ✅ Divider */}
            <hr className="my-6" />

            {/* ✅ Product Tax Group */}
            <label className="font-medium flex items-center gap-1 mb-2">
                Product tax group
                <Info size={16} className="text-orange-500" />
            </label>

            <select className="border rounded-lg p-3 w-full bg-white">
                <option>Products (default rate)</option>
            </select>

            {/* ✅ ----------- MEDIA SECTION ----------- */}
            <h2 className="text-xl font-semibold mt-10 mb-2">Media</h2>
            {/* ✅ Media Section */}
            <label className="text-sm font-medium">Media (max 15)</label>

            {/* ✅ When no media uploaded */}
            {media.length === 0 ? (
                <div
                    onClick={() => fileInputRef.current.click()}
                    className="border-2 border-dashed rounded-lg h-40 mt-2 flex flex-col justify-center items-center cursor-pointer hover:border-orange-500 hover:bg-orange-50 transition"
                >
                    <UploadCloud className="text-orange-500 mb-1" size={38} />
                    <p>Click to upload</p>
                </div>
            ) : (
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 mt-3">
                    <ReactSortable
                        list={media}
                        setList={setMedia}
                        animation={200}
                        className="contents"
                    >
                        {media.map((m, i) => (
                            <div
                                key={m.id}
                                className="relative h-40 border rounded-lg overflow-hidden group"
                            >
                                {/* ✅ Image or Video */}
                                {m.type?.includes("video") ? (
                                    <video
                                        src={m.preview || m.url}
                                        className="w-full h-full object-cover"
                                        muted
                                    />
                                ) : (
                                    <img
                                        src={m.preview || m.url}
                                        className="w-full h-full object-cover"
                                    />
                                )}

                                {/* ✅ Main Tag */}
                                {i === 0 && (
                                    <span className="absolute top-2 left-2 bg-black text-white text-xs px-2 py-1 rounded">
                                        MAIN
                                    </span>
                                )}

                                {/* ✅ Delete Button */}
                                <button
                                    onClick={() => removeItem(m.id)}
                                    className="absolute top-2 right-2 bg-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition"
                                >
                                    <X size={14} />
                                </button>
                            </div>
                        ))}
                    </ReactSortable>

                    {/* ✅ ✅ Add More Button (your missing part) */}
                    {media.length < 15 && (
                        <div
                            onClick={() => fileInputRef.current.click()}
                            className="flex flex-col items-center justify-center border-2 border-dashed rounded-lg h-40 cursor-pointer hover:border-orange-500 hover:bg-orange-50 transition"
                        >
                            <UploadCloud className="text-orange-500 mb-2" size={28} />
                            <p className="text-sm">Add Media</p>
                        </div>
                    )}
                </div>
            )}

            <input
                type="file"
                multiple
                ref={fileInputRef}
                accept="image/*,video/*"
                onChange={handleUpload}
                className="hidden"
            />

        </section>
    );
}
