import React, { useEffect, useState } from "react";
import { toast } from "sonner";
import { X } from "lucide-react";

/* -------------------------------------------------------------------------- */
/*                                    Drawer                                   */
/* -------------------------------------------------------------------------- */
function Drawer({ open, onClose, title, children }) {
    if (!open) return null;

    return (
        <div className="fixed inset-0 z-[70] flex justify-end">
            <div
                className="absolute inset-0 bg-black/40"
                onClick={onClose}
            />

            <div className="relative bg-white w-full max-w-md h-full shadow-xl overflow-y-auto">
                <div className="flex items-center justify-between px-5 py-4 border-b">
                    <h2 className="text-lg font-semibold">{title}</h2>
                    <button
                        onClick={onClose}
                        className="p-2 rounded hover:bg-slate-100"
                    >
                        <X size={18} />
                    </button>
                </div>

                <div className="p-5">{children}</div>
            </div>
        </div>
    );
}

/* -------------------------------------------------------------------------- */
/*                          COLOR HEX FOR SWATCHES                            */
/* -------------------------------------------------------------------------- */
const colorHex = (value) => {
    const map = {
        Red: "#FF4A4A",
        Blue: "#4A6CFF",
        Green: "#52C41A",
        Yellow: "#FFD43B",
        Black: "#000000",
        White: "#FFFFFF",
        Pink: "#FF7EB6",
        Purple: "#9B59B6",
        Orange: "#FF8C00",
        Gray: "#7F8C8D",
    };
    return map[value] || "#999";
};

/* -------------------------------------------------------------------------- */
/*                               MAIN COMPONENT                                */
/* -------------------------------------------------------------------------- */
export default function Variants({ options = [], variants, setVariants }) {
    const [editIndex, setEditIndex] = useState(null);
    const [editData, setEditData] = useState({});
    const [drawerOpen, setDrawerOpen] = useState(false);

    /* ---------------------------- Generate Variants ---------------------------- */
    useEffect(() => {
        if (!options.length) {
            setVariants([]);
            return;
        }

        // Prevent re-generating if structure hasn’t changed
        if (variants.length > 0) {
            const oldKeys = Object.keys(variants[0].optionCombination || {});
            const newKeys = options.map((o) => o.name);
            if (JSON.stringify(oldKeys) === JSON.stringify(newKeys)) return;
        }

        let combos = [[]];
        options.forEach((opt) => {
            combos = combos
                .map((c) => opt.values.map((v) => [...c, { [opt.name]: v }]))
                .flat();
        });

        const newList = combos.map((combo) => {
            const combination = {};
            combo.forEach((c) => Object.assign(combination, c));

            return {
                optionCombination: combination,
                price: "",
                strikethroughPrice: "",
                stockQuantity: 0,
                inventoryTracked: true,
                preOrder: false,
                preOrderLimit: "",
                costOfGoods: "",
                sku: "",
                barcode: "",
                shippingEnabled: false,
                shippingWeight: "",
                shippingUnit: "g",
            };
        });

        setVariants(newList);
    }, [JSON.stringify(options)]);

    /* ------------------------------- Open Drawer ------------------------------- */
    const openEditor = (index) => {
        setEditIndex(index);
        setEditData({ ...variants[index] });
        setDrawerOpen(true);
    };

    /* ------------------------------- Save Drawer ------------------------------- */
    const saveVariant = () => {
        const updated = [...variants];
        updated[editIndex] = editData;
        setVariants(updated);
        toast.success("Variant updated");
        setDrawerOpen(false);
    };

    /* ---------------------------- Utility ---------------------------- */
    const getVariantLabel = (obj) => Object.values(obj).join(" / ");

    /* -------------------------------------------------------------------------- */
    /*                                   RENDER                                   */
    /* -------------------------------------------------------------------------- */
    return (
        <section className="bg-white rounded-xl border-none shadow-sm overflow-hidden">
            {/* Header */}
            <div className="px-5 py-4 border-b">
                <div className="flex items-center justify-between">
                    <h2 className="text-lg font-semibold">Variants</h2>
                    <span className="text-sm text-slate-600">
                        {variants.length} Variants
                    </span>
                </div>
                <p className="text-sm text-slate-500 mt-1">
                    Manage pricing, inventory and more for each product variant.
                </p>
            </div>

            {/* Table Header */}
            <div className="grid grid-cols-12 px-5 py-3 text-xs font-medium text-slate-600 bg-slate-50 border-b">
                <div className="col-span-6">Variant</div>
                <div className="col-span-2 text-center">Price</div>
                <div className="col-span-2 text-center">Inventory</div>
                <div className="col-span-2 text-right">Action</div>
            </div>

            {/* Variant Rows */}
            {variants.map((v, i) => {
                const variantLabel = getVariantLabel(v.optionCombination);

                return (
                    <div
                        key={i}
                        className="grid grid-cols-12 px-5 py-4 border-b items-center"
                    >
                        <div className="col-span-6">
                            <div className="font-medium">{variantLabel}</div>

                            <div className="flex gap-2 mt-1">
                                {Object.entries(v.optionCombination).map(
                                    ([key, val]) =>
                                        key.toLowerCase() === "color" && (
                                            <div
                                                key={val}
                                                className="w-5 h-5 rounded-full border"
                                                style={{ backgroundColor: colorHex(val) }}
                                            ></div>
                                        )
                                )}
                            </div>
                        </div>

                        <div className="col-span-2 text-center text-sm">
                            {v.price ? `₹${v.price}` : "--"}
                        </div>

                        <div className="col-span-2 text-center text-sm">
                            {v.inventoryTracked ? v.stockQuantity : "Off"}
                        </div>

                        <div className="col-span-2 flex justify-end">
                            <button
                                onClick={() => openEditor(i)}
                                className="px-3 py-1.5 border border-none bg-orange-500 rounded hover:bg-orange-600 text-sm text-white"
                            >
                                Edit
                            </button>
                        </div>
                    </div>
                );
            })}

            {/* Drawer Editor */}
            <Drawer
                open={drawerOpen}
                onClose={() => setDrawerOpen(false)}
                title="Edit Variant"
            >
                <div className="text-sm text-slate-600 mb-4">
                    {editData.optionCombination &&
                        getVariantLabel(editData.optionCombination)}
                </div>

                <div className="space-y-4">
                    <div>
                        <label className="text-sm font-medium">Price</label>
                        <input
                            type="number"
                            className="mt-1 w-full border rounded-md px-3 py-2"
                            value={editData.price || ""}
                            onChange={(e) =>
                                setEditData({ ...editData, price: e.target.value })
                            }
                        />
                    </div>

                    <div>
                        <label className="text-sm font-medium">Strikethrough Price</label>
                        <input
                            type="number"
                            className="mt-1 w-full border rounded-md px-3 py-2"
                            value={editData.strikethroughPrice || ""}
                            onChange={(e) =>
                                setEditData({
                                    ...editData,
                                    strikethroughPrice: e.target.value,
                                })
                            }
                        />
                    </div>

                    <div className="flex items-center justify-between border rounded-md p-3">
                        <span className="text-sm font-medium">Track Inventory</span>
                        <input
                            type="checkbox"
                            checked={editData.inventoryTracked}
                            onChange={(e) =>
                                setEditData({
                                    ...editData,
                                    inventoryTracked: e.target.checked,
                                })
                            }
                        />
                    </div>

                    {editData.inventoryTracked && (
                        <div>
                            <label className="text-sm font-medium">Quantity</label>
                            <select
                                className="mt-1 w-full border rounded-md px-3 py-2"
                                value={editData.stockQuantity}
                                onChange={(e) =>
                                    setEditData({
                                        ...editData,
                                        stockQuantity: e.target.value,
                                    })
                                }
                            >
                                {[...Array(501).keys()].map((n) => (
                                    <option key={n}>{n}</option>
                                ))}
                            </select>
                        </div>
                    )}

                    <div className="space-y-2">
                        <div className="flex items-center justify-between border rounded-md p-3">
                            <span className="text-sm font-medium">Allow Pre-order</span>
                            <input
                                type="checkbox"
                                checked={editData.preOrder}
                                onChange={(e) =>
                                    setEditData({
                                        ...editData,
                                        preOrder: e.target.checked,
                                    })
                                }
                            />
                        </div>

                        {editData.preOrder && (
                            <div>
                                <label className="text-sm font-medium">Pre-order Limit</label>
                                <input
                                    type="number"
                                    className="mt-1 w-full border rounded-md px-3 py-2"
                                    value={editData.preOrderLimit || ""}
                                    onChange={(e) =>
                                        setEditData({
                                            ...editData,
                                            preOrderLimit: e.target.value,
                                        })
                                    }
                                />
                            </div>
                        )}
                    </div>

                    <div>
                        <label className="text-sm font-medium">Cost of Goods</label>
                        <input
                            type="number"
                            className="mt-1 w-full border rounded-md px-3 py-2"
                            value={editData.costOfGoods || ""}
                            onChange={(e) =>
                                setEditData({
                                    ...editData,
                                    costOfGoods: e.target.value,
                                })
                            }
                        />
                    </div>

                    <div>
                        <label className="text-sm font-medium">SKU</label>
                        <input
                            className="mt-1 w-full border rounded-md px-3 py-2"
                            value={editData.sku || ""}
                            onChange={(e) =>
                                setEditData({ ...editData, sku: e.target.value })
                            }
                        />
                    </div>

                    <div>
                        <label className="text-sm font-medium">Barcode (GSIN)</label>
                        <input
                            className="mt-1 w-full border rounded-md px-3 py-2"
                            value={editData.barcode || ""}
                            onChange={(e) =>
                                setEditData({ ...editData, barcode: e.target.value })
                            }
                        />
                    </div>

                    <div className="flex items-center justify-between border rounded-md p-3">
                        <span className="text-sm font-medium">Enable Shipping</span>
                        <input
                            type="checkbox"
                            checked={editData.shippingEnabled}
                            onChange={(e) =>
                                setEditData({
                                    ...editData,
                                    shippingEnabled: e.target.checked,
                                })
                            }
                        />
                    </div>

                    {editData.shippingEnabled && (
                        <div className="flex gap-3">
                            <input
                                type="number"
                                className="border rounded-md px-3 py-2 w-full"
                                value={editData.shippingWeight || ""}
                                onChange={(e) =>
                                    setEditData({
                                        ...editData,
                                        shippingWeight: e.target.value,
                                    })
                                }
                                placeholder="Weight"
                            />

                            <select
                                className="border rounded-md px-3 py-2"
                                value={editData.shippingUnit}
                                onChange={(e) =>
                                    setEditData({
                                        ...editData,
                                        shippingUnit: e.target.value,
                                    })
                                }
                            >
                                <option value="g">g</option>
                                <option value="kg">kg</option>
                                <option value="ml">ml</option>
                                <option value="L">L</option>
                                <option value="lb">lb</option>
                                <option value="oz">oz</option>
                            </select>
                        </div>
                    )}
                </div>

                <button
                    onClick={saveVariant}
                    className="mt-6 w-full bg-orange-500 text-white py-2 rounded-md hover:bg-orange-600"
                >
                    Save Variant
                </button>
            </Drawer>
        </section>
    );
}
