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

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

    return (
        <div className="fixed inset-0 z-[80] flex items-center justify-center">
            <div
                className="absolute inset-0 bg-black/40 backdrop-blur-sm"
                onClick={onClose}
            />
            <div className="relative w-full max-w-xl bg-white rounded-xl shadow-xl border animate-scaleIn">
                <div className="flex items-center justify-between px-6 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-6">{children}</div>

                <div className="px-6 py-4 border-t flex justify-end gap-3">
                    {footer}
                </div>
            </div>
        </div>
    );
}

/* ---------------------------------------------------
   Main Component
--------------------------------------------------- */
export default function Modifiers({ modifiers, setModifiers }) {
    const [modalOpen, setModalOpen] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editIndex, setEditIndex] = useState(null);

    const [name, setName] = useState("");
    const [type, setType] = useState("dropdown");
    const [required, setRequired] = useState(false);
    const [choicesText, setChoicesText] = useState("");
    const [charLimit, setCharLimit] = useState(500);

    const resetModal = () => {
        setName("");
        setType("dropdown");
        setRequired(false);
        setChoicesText("");
        setCharLimit(500);
        setIsEditing(false);
        setEditIndex(null);
    };

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

    const openEdit = (index) => {
        const m = modifiers[index];
        setIsEditing(true);
        setEditIndex(index);

        setName(m.name);
        setType(m.type);
        setRequired(m.required);

        if (m.type === "text") {
            setCharLimit(m.characterLimit);
        } else {
            setChoicesText(m.choices.join(", "));
        }

        setModalOpen(true);
    };

    const saveModifier = () => {
        if (!name.trim()) {
            toast.error("Modifier name is required");
            return;
        }

        let newModifier = {
            id: isEditing ? modifiers[editIndex].id : crypto.randomUUID(),
            name,
            type,
            required,
        };

        if (type === "text") {
            newModifier.characterLimit = charLimit;
            newModifier.choices = [];
        } else {
            const choices = choicesText
                .split(/[,\n]/)
                .map((v) => v.trim())
                .filter(Boolean);

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

            newModifier.choices = choices;
        }

        let updated = [];

        if (isEditing) {
            updated = [...modifiers];
            updated[editIndex] = newModifier;
            toast.success("Modifier updated");
        } else {
            updated = [...modifiers, newModifier];
            toast.success("Modifier added");
        }

        setModifiers(updated);
        setModalOpen(false);
        resetModal();
    };

    const removeModifier = (index) => {
        const list = [...modifiers];
        toast.success(`"${list[index].name}" removed`);
        list.splice(index, 1);
        setModifiers(list);
    };

    return (
        <section className="bg-white rounded-xl border-none shadow-sm">
            {/* Header */}
            <div className="flex items-center justify-between px-5 py-4 border-b">
                <h2 className="text-lg font-semibold flex items-center gap-2">
                    Modifiers
                    <span className="text-[11px] px-2 py-[2px] bg-slate-100 rounded-full text-slate-600">
                        {modifiers.length} / 10
                    </span>
                </h2>
            </div>

            {/* Info */}
            {modifiers.length === 0 && (
                <div className="px-5 py-6 text-slate-600 text-sm">
                    Offer customization options that don’t require special prices or inventory,
                    like made-to-order embroidery patterns or engraving custom text.
                </div>
            )}

            {/* Modifier List */}
            <div>
                {modifiers.map((m, i) => (
                    <div
                        key={m.id}
                        className="flex items-center justify-between px-5 py-4 border-b hover:bg-slate-50"
                    >
                        <div>
                            <div className="font-medium">{m.name}</div>
                            <div className="text-xs text-slate-500 mt-1">
                                {m.type === "dropdown" && `${m.choices.length} choices`}
                                {m.type === "color" && `${m.choices.length} colors`}
                                {m.type === "text" && `Text box (${m.characterLimit} chars)`}
                            </div>
                        </div>

                        <div className="relative">
                            <button
                                onClick={() => openEdit(i)}
                                className="mr-4 text-gray-400 text-sm hover:underline"
                            >
                                Edit
                            </button>

                            <button
                                onClick={() => removeModifier(i)}
                                className="text-orange-500 text-sm hover:underline"
                            >
                                Remove
                            </button>
                        </div>
                    </div>
                ))}
            </div>

            {/* Add Button */}
            <div className="px-5 py-4">
                <button
                    onClick={openAdd}
                    className="flex items-center gap-2 text-orange-500 hover:text-orange-6bg-00"
                >
                    <Plus size={18} /> Add Modifier
                </button>
            </div>

            {/* Modal */}
            <Modal
                open={modalOpen}
                title={isEditing ? "Edit modifier" : "Add modifier"}
                onClose={() => setModalOpen(false)}
                footer={
                    <>
                        <button
                            className="px-4 py-2 rounded-md bg-gray-200 cursor-pointer hover:bg-gray-300"
                            onClick={() => setModalOpen(false)}
                        >
                            Cancel
                        </button>
                        <button
                            className="px-4 py-2 rounded-md cursor-pointer bg-orange-500 text-white hover:bg-orange-600"
                            onClick={saveModifier}
                        >
                            {isEditing ? "Save" : "Add"}
                        </button>
                    </>
                }
            >
                <p className="text-sm text-slate-500 mb-4">
                    Let customers personalize their product with modifiers like custom text or embroidery.
                </p>

                {/* Name */}
                <div className="mb-5">
                    <label className="text-sm font-medium">Modifier name (internal)</label>
                    <input
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        className="mt-1 w-full border rounded-md px-3 py-2"
                        placeholder="e.g., Engraving"
                    />
                </div>

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

                {/* Required toggle */}
                <div className="mb-5 flex items-center gap-3">
                    <input
                        type="checkbox"
                        checked={required}
                        onChange={(e) => setRequired(e.target.checked)}
                    />
                    <span className="text-sm">This is a required field</span>
                </div>

                {/* Dropdown or Color choices */}
                {type !== "text" && (
                    <div className="mb-5">
                        <label className="text-sm font-medium">Choices</label>
                        <input
                            value={choicesText}
                            onChange={(e) => setChoicesText(e.target.value)}
                            className="mt-1 w-full border rounded-md px-3 py-2"
                            placeholder="e.g., Red, Blue, Green"
                        />
                    </div>
                )}

                {/* Text Box Character Limit */}
                {type === "text" && (
                    <div className="mb-5">
                        <label className="text-sm font-medium">Character limit</label>
                        <input
                            type="number"
                            value={charLimit}
                            onChange={(e) =>
                                setCharLimit(Math.max(1, Number(e.target.value)))
                            }
                            className="mt-1 w-full border rounded-md px-3 py-2"
                        />
                    </div>
                )}
            </Modal>
        </section>
    );
}
