import React, { useState, useEffect } from "react";
import { Check, ChevronDown, ChevronUp } from "lucide-react";

export default function ProductDetails({ product, setMainImage, API }) {
    const [selectedOptions, setSelectedOptions] = useState(() => {
        if (!product?._id) return {};
        const saved = localStorage.getItem(`options-${product._id}`);
        return saved ? JSON.parse(saved) : {};
    });

    const [selectedModifiers, setSelectedModifiers] = useState(() => {
        if (!product?._id) return {};
        const saved = localStorage.getItem(`modifiers-${product._id}`);
        return saved ? JSON.parse(saved) : {};
    });

    const [currentVariant, setCurrentVariant] = useState(null);
    const [openSection, setOpenSection] = useState(null);

    useEffect(() => {
        if (product?._id)
            localStorage.setItem(`options-${product._id}`, JSON.stringify(selectedOptions));
    }, [selectedOptions, product?._id]);

    useEffect(() => {
        if (product?._id)
            localStorage.setItem(`modifiers-${product._id}`, JSON.stringify(selectedModifiers));
    }, [selectedModifiers, product?._id]);

    useEffect(() => {
        if (!product?.variants?.length) return;
        const variant = product.variants.find((v) => {
            const combo = Object.entries(selectedOptions);
            return combo.every(([key, val]) => v.optionCombination[key] === val);
        });
        setCurrentVariant(variant || null);
    }, [selectedOptions, product]);

    const handleOptionChange = (name, value) =>
        setSelectedOptions((prev) => ({ ...prev, [name]: value }));

    const handleModifierChange = (name, value) =>
        setSelectedModifiers((prev) => ({ ...prev, [name]: value }));

    const inStock =
        product.trackInventory || currentVariant?.stockQuantity > 0
            ? product.stockQuantity > 0 || currentVariant?.stockQuantity > 0
            : product.status === "in_stock";

    const discount =
        product.strikethroughPrice && product.price
            ? Math.round(
                ((product.strikethroughPrice - product.price) / product.strikethroughPrice) * 100
            )
            : 0;

    const toggleSection = (id) => {
        setOpenSection(openSection === id ? null : id);
    };

    return (
        <div>
            {/* ------------------- TITLE ------------------- */}
            <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900 leading-tight">
                {product.name}
            </h1>
            <p className="text-gray-500 mt-1 text-sm">Brand: {product.brand}</p>

            {/* ------------------- DESCRIPTION ------------------- */}
            <div className="mt-6 text-gray-700 leading-relaxed text-[15px]">
                <p dangerouslySetInnerHTML={{ __html: product.description }} />
            </div>

            {/* ------------------- PRICE ------------------- */}
            <div className="mt-4 flex items-end gap-2">
                <p className="text-3xl font-bold text-gray-900">
                    ₹{currentVariant?.price || product.price}
                </p>
                {product.strikethroughPrice && (
                    <p className="text-lg line-through text-gray-400">
                        ₹{product.strikethroughPrice}
                    </p>
                )}
                {discount > 0 && (
                    <span className="text-sm text-green-600 font-medium">{discount}% off</span>
                )}
            </div>

            {/* ------------------- STOCK ------------------- */}
            <div className="mt-3">
                {inStock ? (
                    <p className="text-sm text-green-600 font-medium flex items-center gap-1">
                        <Check size={16} /> In Stock
                    </p>
                ) : (
                    <p className="text-sm text-red-600 font-medium">Out of Stock</p>
                )}
            </div>

            {/* ------------------- OPTIONS ------------------- */}
            {product.options?.length > 0 && (
                <div className="mt-6 space-y-6">
                    {product.options.map((opt) => (
                        <div key={opt.name}>
                            <p className="font-medium text-gray-800 mb-2 capitalize">
                                {opt.name}:
                                {selectedOptions[opt.name] && (
                                    <span className="ml-2 text-orange-500 font-semibold">
                                        {selectedOptions[opt.name]}
                                    </span>
                                )}
                            </p>

                            {opt.type === "color" ? (
                                <div className="flex flex-wrap gap-3">
                                    {opt.values.map((colorName, i) => {
                                        const selected = selectedOptions[opt.name] === colorName;
                                        const imageUrl = opt.images?.[i];
                                        return (
                                            <div
                                                key={i}
                                                onClick={() => {
                                                    handleOptionChange(opt.name, colorName);
                                                    const variant = product.variants.find(
                                                        (v) => v.optionCombination[opt.name] === colorName
                                                    );
                                                    if (variant?.media?.[0]?.url)
                                                        setMainImage(`${API}${variant.media[0].url}`);
                                                }}
                                                className={`relative w-14 h-14 rounded-md border-2 cursor-pointer overflow-hidden transition-all ${selected
                                                    ? "border-gray-200 scale-105"
                                                    : "border-gray-300 hover:border-orange-300"
                                                    }`}
                                            >
                                                {imageUrl ? (
                                                    <img
                                                        src={`${API}${imageUrl}`}
                                                        alt={colorName}
                                                        className="object-cover w-full h-full"
                                                    />
                                                ) : (
                                                    <div
                                                        className="w-full h-full"
                                                        style={{ backgroundColor: colorName.toLowerCase() }}
                                                    ></div>
                                                )}
                                            </div>
                                        );
                                    })}
                                </div>
                            ) : (
                                <div className="flex flex-wrap gap-2">
                                    {opt.values.map((val, i) => {
                                        const selected = selectedOptions[opt.name] === val;
                                        return (
                                            <button
                                                key={i}
                                                onClick={() => handleOptionChange(opt.name, val)}
                                                className={`px-4 py-2 rounded-md border text-sm font-medium transition-all ${selected
                                                    ? "border-orange-300 text-orange-500 bg-orange-50"
                                                    : "border-gray-300 text-gray-800 hover:border-orange-300"
                                                    }`}
                                            >
                                                {val}
                                            </button>
                                        );
                                    })}
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            )}

            {/* ------------------- MODIFIERS ------------------- */}
            {product.modifiers?.length > 0 && (
                <div className="mt-8 border-t pt-6">
                    <h3 className="font-semibold text-gray-800 mb-4">
                        Customize your product
                    </h3>

                    {product.modifiers
                        .sort((a, b) => a.order - b.order)
                        .map((mod, i) => (
                            <div key={mod.id || i} className="mb-6">
                                <p className="font-medium text-gray-700 mb-2">
                                    {mod.name}
                                    {mod.required && <span className="text-red-500 ml-1">*</span>}
                                </p>

                                {mod.type === "dropdown" && (
                                    <select
                                        required={mod.required}
                                        className="border rounded-md p-2 w-full text-gray-700 focus:ring-2 focus:ring-blue-400"
                                        onChange={(e) => handleModifierChange(mod.name, e.target.value)}
                                        value={selectedModifiers[mod.name] || ""}
                                    >
                                        <option value="">Select {mod.name}</option>
                                        {mod.choices.map((choice, j) => (
                                            <option key={j} value={choice}>
                                                {choice}
                                            </option>
                                        ))}
                                    </select>
                                )}

                                {mod.type === "color" && (
                                    <div className="flex flex-wrap gap-3">
                                        {mod.choices.map((colorObj, j) => {
                                            const color =
                                                typeof colorObj === "string" ? colorObj : colorObj.name;
                                            const imageUrl =
                                                typeof colorObj === "object" ? colorObj.imageUrl : null;
                                            const selected = selectedModifiers[mod.name] === color;
                                            return (
                                                <div
                                                    key={j}
                                                    onClick={() => handleModifierChange(mod.name, color)}
                                                    className={`w-12 h-12 rounded-md border-2 cursor-pointer overflow-hidden transition-all ${selected
                                                        ? "border-blue-600 scale-105"
                                                        : "border-gray-300 hover:border-blue-400"
                                                        }`}
                                                >
                                                    {imageUrl ? (
                                                        <img
                                                            src={`${API}${imageUrl}`}
                                                            alt={color}
                                                            className="object-cover w-full h-full"
                                                        />
                                                    ) : (
                                                        <div
                                                            className="w-full h-full"
                                                            style={{
                                                                backgroundColor: color.toLowerCase(),
                                                            }}
                                                        ></div>
                                                    )}
                                                </div>
                                            );
                                        })}
                                    </div>
                                )}

                                {mod.type === "text" && (
                                    <input
                                        type="text"
                                        required={mod.required}
                                        placeholder={`Enter ${mod.name}`}
                                        maxLength={mod.characterLimit || 100}
                                        className="border rounded-md p-2 w-full text-gray-700 focus:ring-2 focus:ring-blue-400"
                                        value={selectedModifiers[mod.name] || ""}
                                        onChange={(e) =>
                                            handleModifierChange(mod.name, e.target.value)
                                        }
                                    />
                                )}
                            </div>
                        ))}
                </div>
            )}



            {/* ------------------- INFO SECTIONS (Accordion) ------------------- */}
            {product.infoSections?.length > 0 && (
                <div className="mt-10 border-t pt-6">
                    <h2 className="text-xl font-semibold mb-4 text-gray-800">
                        Product Details
                    </h2>
                    <div className="divide-y border rounded-lg overflow-hidden">
                        {product.infoSections
                            .sort((a, b) => a.order - b.order)
                            .map((section, i) => (
                                <div key={section.id || i} className="border-b">
                                    <button
                                        onClick={() => toggleSection(section.id || i)}
                                        className="w-full flex justify-between items-center px-4 py-3 text-left font-medium text-gray-800 hover:bg-gray-50"
                                    >
                                        {section.customTitle || section.title}
                                        {openSection === (section.id || i) ? (
                                            <ChevronUp size={18} />
                                        ) : (
                                            <ChevronDown size={18} />
                                        )}
                                    </button>
                                    {openSection === (section.id || i) && (
                                        <div
                                            className="px-4 pb-4 text-gray-700 text-sm leading-relaxed"
                                            dangerouslySetInnerHTML={{
                                                __html: section.customHtml || section.html,
                                            }}
                                        />
                                    )}
                                </div>
                            ))}
                    </div>
                </div>
            )}
        </div>
    );
}
