import React, { useState, useRef } from "react";
import { Plus, X, UploadCloud } from "lucide-react";
import { ReactSortable } from "react-sortablejs";
import { toast } from "sonner";

/* -----------------------------------------
   SMALL UI COMPONENTS
----------------------------------------- */
function Pill({ children }) {
    return (
        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-slate-100 text-slate-700 text-xs font-medium">
            {children}
        </span>
    );
}

function Modal({ open, onClose, title, children, footer }) {
    if (!open) return null;

    return (
        <div className="fixed inset-0 z-[60] flex items-center justify-center">
            <div
                onClick={onClose}
                className="absolute inset-0 bg-black/40 backdrop-blur-sm"
            />
            <div className="relative w-[95%] max-w-2xl bg-white rounded-xl shadow-xl border">
                <div className="flex items-center justify-between px-6 py-4 border-b">
                    <h3 className="text-lg font-semibold">{title}</h3>
                    <button
                        onClick={onClose}
                        className="p-2 rounded hover:bg-slate-100 text-slate-600"
                    >
                        <X size={20} />
                    </button>
                </div>
                <div className="p-6">{children}</div>
                <div className="flex items-center justify-end gap-3 px-6 py-4 border-t">
                    {footer}
                </div>
            </div>
        </div>
    );
}

/* -----------------------------------------
   MAIN COMPONENT
----------------------------------------- */
export default function ProductOptions({
    options = [],
    setOptions,
    variants = [],
    setVariants,
}) {
    const [modalOpen, setModalOpen] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editIndex, setEditIndex] = useState(null);

    const [optName, setOptName] = useState("");
    const [fieldType, setFieldType] = useState("dropdown");
    const [choicesText, setChoicesText] = useState("");
    const [colorImages, setColorImages] = useState([]);
    const colorFileRef = useRef(null);

    /* -----------------------------------------
       MODAL HANDLERS
    ----------------------------------------- */
    const resetModal = () => {
        setOptName("");
        setFieldType("dropdown");
        setChoicesText("");
        setColorImages([]);
        setIsEditing(false);
        setEditIndex(null);
    };

    const openAddModal = () => {
        resetModal();
        setModalOpen(true);
    };

    const openEditModal = (index) => {
        const opt = options[index];
        setIsEditing(true);
        setEditIndex(index);
        setOptName(opt.name);
        setFieldType(opt.type || "dropdown");
        setChoicesText(opt.values.join(", "));
        setColorImages(
            (opt.images || []).map((img) =>
                typeof img === "string" ? { url: img } : img
            )
        );
        setModalOpen(true);
    };


    /* -----------------------------------------
       SAVE ADD/EDIT
    ----------------------------------------- */
    const saveOption = () => {
        const name = optName.trim();
        if (!name) return toast.error("Option name is required");

        const values = choicesText
            .split(/[,\n]/)
            .map((v) => v.trim())
            .filter(Boolean);

        if (values.length === 0) return toast.error("Add at least one choice");

        // Duplicate check
        if (
            options.some(
                (o, i) =>
                    i !== editIndex && o.name.toLowerCase() === name.toLowerCase()
            )
        ) {
            return toast.error(`"${name}" already exists`);
        }

        const newOption = {
            name,
            values,
            type: fieldType,
            images:
                fieldType === "color"
                    ? colorImages.map(
                        (file) => file.preview || file.url || file.name || ""
                    )
                    : [],
        };

        let updatedOptions = [...options];
        if (isEditing) {
            updatedOptions[editIndex] = newOption;
            toast.success(`"${name}" updated`);
        } else {
            updatedOptions.push(newOption);
            toast.success(`"${name}" added`);
        }

        setOptions(updatedOptions);
        regenerateVariants(updatedOptions);
        resetModal();
        setModalOpen(false);
    };

    /* -----------------------------------------
       REMOVE OPTION
    ----------------------------------------- */
    const removeOption = (index) => {
        const removed = options[index];
        const updatedOptions = options.filter((_, i) => i !== index);
        toast.success(`"${removed.name}" removed`);
        setOptions(updatedOptions);
        regenerateVariants(updatedOptions);
    };

    /* -----------------------------------------
       REGENERATE VARIANTS
    ----------------------------------------- */
    const regenerateVariants = (opts) => {
        if (opts.length === 0) {
            setVariants([]);
            return;
        }

        const combos = cartesian(
            Object.fromEntries(opts.map((o) => [o.name, o.values]))
        );

        const newVariants = combos.map((comb) => {
            const key = Object.entries(comb)
                .map(([k, v]) => `${k}:${v}`)
                .join("|");

            return {
                key,
                optionCombination: comb,
                price: "",
                strikethroughPrice: "",
                sku: "",
                barcode: "",
                stockQuantity: 0,
                inStock: true,
            };
        });

        setVariants(newVariants);
    };

    function cartesian(obj) {
        const keys = Object.keys(obj);
        if (keys.length === 0) return [];
        return keys.reduce(
            (acc, key) =>
                acc.flatMap((item) => obj[key].map((val) => ({ ...item, [key]: val }))),
            [{}]
        );
    }

    /* -----------------------------------------
       RENDER
    ----------------------------------------- */
    return (
        <section className="bg-white rounded-xl shadow-sm border-none overflow-hidden">
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-4">
                <div className="flex items-center gap-3">
                    <h2 className="text-lg font-semibold">Product options</h2>
                    <span className="text-[11px] rounded-full bg-slate-100 px-2 py-[2px] text-slate-700">
                        {options.length} / added
                    </span>
                </div>
                <div className="text-sm text-slate-500">
                    Add options like size or color to create variants.
                </div>
            </div>

            {/* Options List */}
            <div className="border-t">
                {options.length === 0 ? (
                    <div className="px-5 py-6 text-slate-600">
                        To create variants, add product options like sizes or colors.
                    </div>
                ) : (
                    options.map((opt, i) => (
                        <div
                            key={i}
                            className="flex items-center justify-between gap-4 px-5 py-4 border-b"
                        >
                            <div className="flex items-start gap-3">
                                <div className="mt-[6px] h-4 w-1 rounded-full bg-slate-300" />
                                <div>
                                    <div className="font-medium flex items-center gap-2">
                                        {opt.name}
                                    </div>

                                    <div className="mt-2 flex flex-wrap gap-2">
                                        {opt.values.slice(0, 3).map((v, index) => (
                                            <Pill key={index}>{v}</Pill>
                                        ))}
                                        {opt.values.length > 3 && (
                                            <span className="text-xs bg-blue-50 text-orange-500 px-2 py-0.5 rounded-full">
                                                +{opt.values.length - 3} more
                                            </span>
                                        )}
                                    </div>

                                    <div className="text-xs text-slate-400 mt-1">
                                        Type:{" "}
                                        {opt.type === "color" ? "Color swatches" : "Dropdown list"}
                                    </div>
                                </div>
                            </div>

                            <div className="flex items-center gap-3">
                                <button
                                    onClick={() => openEditModal(i)}
                                    className="px-3 py-2 text-sm rounded-md border hover:bg-slate-50"
                                >
                                    Edit
                                </button>
                                <button
                                    onClick={() => removeOption(i)}
                                    className="px-3 py-2 text-sm rounded-md border hover:bg-slate-50"
                                >
                                    Remove
                                </button>
                            </div>
                        </div>
                    ))
                )}
            </div>

            {/* Add Option */}
            <div className="px-5 py-4">
                <button
                    onClick={openAddModal}
                    className="inline-flex items-center gap-2 cursor-pointer text-orange-500 hover:text-orange-600"
                >
                    <Plus size={18} /> Add Option
                </button>
            </div>

            {/* Modal */}
            <Modal
                open={modalOpen}
                onClose={() => {
                    resetModal();
                    setModalOpen(false);
                }}
                title={isEditing ? "Edit product option" : "Add product option"}
                footer={
                    <>
                        <button
                            onClick={() => {
                                resetModal();
                                setModalOpen(false);
                            }}
                            className="px-4 py-2 bg-gray-200 cursor-pointer hover:bg-gray-300 rounded-md"
                        >
                            Cancel
                        </button>

                        <button
                            onClick={saveOption}
                            className="px-4 py-2 bg-orange-500 text-white rounded-md cursor-pointer hover:bg-orange-600"
                        >
                            {isEditing ? "Save Changes" : "Add"}
                        </button>
                    </>
                }
            >
                <p className="text-sm text-slate-500 mb-4">
                    You can edit values and change field type anytime.
                </p>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Option Name */}
                    <div>
                        <label className="text-sm font-medium">
                            Option name <span className="text-red-500">*</span>
                        </label>

                        <input
                            value={optName}
                            onChange={(e) => {
                                const value = e.target.value;
                                setOptName(value);
                                if (value.toLowerCase().includes("color")) {
                                    setFieldType("color");
                                } else {
                                    setFieldType("dropdown");
                                }
                            }}
                            className="mt-1 w-full rounded-md border px-3 py-2"
                            placeholder="e.g., Size or Color"
                        />
                    </div>

                    {/* Field Type */}
                    <div>
                        <label className="text-sm font-medium">Field type</label>
                        <select
                            value={fieldType}
                            onChange={(e) => setFieldType(e.target.value)}
                            className="mt-1 w-full rounded-md border px-3 py-2 bg-white"
                        >
                            <option value="dropdown">Dropdown list</option>
                            <option value="color">Color swatches</option>
                        </select>
                    </div>

                    {/* Choices */}
                    <div className="md:col-span-2">
                        <label className="text-sm font-medium">Choices *</label>
                        <input
                            value={choicesText}
                            onChange={(e) => setChoicesText(e.target.value)}
                            className="mt-1 w-full rounded-md border px-3 py-2"
                            placeholder="e.g., Red, Blue, Green"
                        />
                        <p className="text-xs text-slate-500 mt-1">
                            Add a comma after each choice.
                        </p>
                    </div>

                    {/* ✅ Color Images Section */}
                    {fieldType === "color" && (
                        <div className="md:col-span-2 mt-2">
                            <label className="text-sm font-medium">
                                Color images (optional)
                            </label>

                            {/* No images uploaded */}
                            {colorImages.length === 0 ? (
                                <div
                                    onClick={() => colorFileRef.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 className="text-sm text-gray-600">
                                        Click to upload color images
                                    </p>
                                </div>
                            ) : (
                                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 mt-3">
                                    <ReactSortable
                                        list={colorImages}
                                        setList={setColorImages}
                                        animation={200}
                                        className="contents"
                                    >
                                        {colorImages.map((img, i) => (
                                            <div
                                                key={i}
                                                className="relative h-40 border rounded-lg overflow-hidden group"
                                            >
                                                <img
                                                    src={
                                                        img.preview ||
                                                        img.url ||
                                                        (typeof img === "string"
                                                            ? img
                                                            : URL.createObjectURL(img))
                                                    }
                                                    alt={`Color ${i + 1}`}
                                                    className="w-full h-full object-cover"
                                                />
                                                <span className="absolute top-2 left-2 bg-black text-white text-xs px-2 py-1 rounded">
                                                    {i + 1}
                                                </span>
                                                <button
                                                    onClick={() =>
                                                        setColorImages(
                                                            colorImages.filter((_, idx) => idx !== i)
                                                        )
                                                    }
                                                    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 */}
                                    {colorImages.length < 15 && (
                                        <div
                                            onClick={() => colorFileRef.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 Images</p>
                                        </div>
                                    )}
                                </div>
                            )}

                            <input
                                type="file"
                                multiple
                                ref={colorFileRef}
                                accept="image/*"
                                onChange={(e) => {
                                    const files = Array.from(e.target.files);
                                    const previews = files.map((f) => ({
                                        ...f,
                                        preview: URL.createObjectURL(f),
                                    }));
                                    setColorImages((prev) => [...prev, ...previews]);
                                }}
                                className="hidden"
                            />

                            <p className="text-xs text-slate-500 mt-1">
                                Upload one image per color (order matters).
                            </p>
                        </div>
                    )}
                </div>
            </Modal>
        </section>
    );
}
