import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { GrLocation } from "react-icons/gr";
import { BiEdit } from "react-icons/bi";
import { FaRegStar } from "react-icons/fa";
import { IoMdCheckmark, IoMdClose } from "react-icons/io";

// Assets
import Bg1 from "../../assets/icons/bg1.svg";
import Vector9 from "../../assets/icons/Vector9.svg";
import Vector11 from "../../assets/icons/Vector11.svg";
import Vector12 from "../../assets/icons/Vector12.svg";
import Vector13 from "../../assets/icons/Vector13.svg";
import Vector14 from "../../assets/icons/Vector14.svg";
import Vector15 from "../../assets/icons/Vector15.svg";
import Vector16 from "../../assets/icons/Vector16.svg";
import Coffee1 from "../../assets/icons/coffee1.svg";
import Coffee2 from "../../assets/icons/coffee2.svg";
import Coffee3 from "../../assets/icons/coffee3.svg";
import Sperso from "../../assets/icons/sperso.svg";
import Edit from "../../assets/icons/edit.svg";

// Services
import cafeService from "../../services/cafe";

// Constants
const DEFAULT_CATEGORIES = [
    "نوشیدنی سرد",
    "نوشیدنی گرم",
    "کیک و دسر",
    "صبحانه",
    "ساندویچ و برگر",
    "سالاد و پیش غذا",
];

const CAFE_FEATURES = [
    { icon: Coffee3, label: "منو کافه:", width: "lg:w-[140px]" },
    { icon: Vector15, label: "ساعت کاری:", value: "23 - 8" },
    { icon: Vector14, label: "رزرو :", value: "رزرو آنلاین" },
    { icon: Vector11, label: "موسیقی :", value: "موسیقی زنده آخر هفته" },
    { icon: Vector13, label: "پارکینگ :", value: "عمومی" },
    { icon: Vector12, label: "دسترسی آسان :", value: "مناسب افراد ناتوان" },
];

const CAFE_PRODUCTS = [
    {
        name: "اسپرسو100%",
        price: "118.000",
        image: Sperso,
        description: "45 میلی لیتر، قهوه، 100% عربیکا، دم شده با دستگاه اسپرسو ساز، به همراه یک عدد آب معدنی مینی",
    },
    {
        name: "کارامل ماکیاتو",
        price: "149.000",
        image: Coffee1,
        description: "220 میلی لیتر، 2 شات اسپرسو 30% روبوستا، 70% عربیکا، یک لکه فوم شیر، سیروپ کارامل",
    },
    {
        name: "اسپرسو آفوگاتو",
        price: "118.000",
        image: Coffee2,
        description: "اسپرسو، یک اسکوپ بستنی وانیلی",
    },
];

export default function EditCafe() {
    const { id } = useParams();
    const navigate = useNavigate();

    // State Management
    const [cafeData, setCafeData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");
    const [categories, setCategories] = useState(() => {
        const saved = localStorage.getItem("cafeCategories");
        return saved ? JSON.parse(saved) : DEFAULT_CATEGORIES;
    });
    const [isEditMode, setIsEditMode] = useState(false);
    const [isAddingCategory, setIsAddingCategory] = useState(false);
    const [newCategory, setNewCategory] = useState("");
    const [editingIndex, setEditingIndex] = useState(null);
    const [editValue, setEditValue] = useState("");

    // Effects
    useEffect(() => {
        fetchCafeData();
    }, [id]);

    useEffect(() => {
        localStorage.setItem("cafeCategories", JSON.stringify(categories));
    }, [categories]);

    // API Calls
    const fetchCafeData = async () => {
        setLoading(true);
        setError("");
        try {
            const res = await cafeService.getCafeList();
            if (res.data.success && res.data.data) {
                const cafe = res.data.data.find((c) => c._id === id);
                if (cafe) {
                    setCafeData(cafe);
                    console.log("✅ Cafe data loaded:", cafe);
                } else {
                    setError("کافه مورد نظر یافت نشد");
                }
            } else {
                setError("داده‌های کافه معتبر نیست");
            }
        } catch (error) {
            console.error("❌ Error loading cafe:", error);
            const errorMessage =
                error.response?.data?.message ||
                (error.request ? "خطا در برقراری ارتباط با سرور" : "خطای نامشخص رخ داده است");
            setError(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    // Category Handlers
    const handleAddCategory = () => {
        if (newCategory.trim()) {
            setCategories([...categories, newCategory.trim()]);
            setNewCategory("");
            setIsAddingCategory(false);
            setTimeout(() => {
                const scrollContainer = document.querySelector(".categories-scroll");
                if (scrollContainer) {
                    scrollContainer.scrollLeft = scrollContainer.scrollWidth;
                }
            }, 0);
        }
    };

    const handleDeleteCategory = (index) => {
        setCategories(categories.filter((_, i) => i !== index));
    };

    const handleEditCategory = (index) => {
        setEditingIndex(index);
        setEditValue(categories[index]);
    };

    const handleSaveCategory = () => {
        if (editValue.trim()) {
            const newCategories = [...categories];
            newCategories[editingIndex] = editValue.trim();
            setCategories(newCategories);
            setEditingIndex(null);
            setEditValue("");
        }
    };

    const handleCancelEdit = () => {
        setEditingIndex(null);
        setEditValue("");
    };

    // Render States
    if (loading) {
        return (
            <div className="flex justify-center items-center h-screen">
                <div className="text-button1 text-2xl font-bold">در حال بارگذاری...</div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="p-6">
                <div className="bg-red-50 border-2 border-red-300 text-red-700 px-4 py-3 rounded-xl">
                    {error}
                </div>
            </div>
        );
    }

    if (!cafeData) {
        return (
            <div className="p-6 text-center text-gray-500">
                اطلاعات کافه یافت نشد
            </div>
        );
    }

        return (
        <section dir="rtl" className="w-full overflow-x-hidden">
            <style>{`
                .scrollbar-hide::-webkit-scrollbar { display: none; }
                .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; }
            `}</style>

            {/* Header */}
            <h1 className="text-[#402E32] font-bold text-lg lg:text-xl mb-6">ادیت {cafeData.Name}</h1>

            {/* Main Container */}
            <div className="border-2 mt-1 border-[#8b8886] p-4 md:p-6 lg:p-10 rounded-2xl">
                {/* Cafe Info Section */}
                <div className="flex flex-col lg:flex-row gap-6 mb-8">
                    {/* Image */}
                    <div className="flex-shrink-0">
                        <img
                            src={cafeData.photo || Bg1}
                            alt={cafeData.Name}
                            className="w-full lg:w-[300px] xl:w-[400px] rounded-lg object-cover"
                        />
                    </div>

                    {/* Info */}
                    <div className="flex-1">
                        {/* Action Buttons */}
                        <div className="flex gap-3 justify-end mb-6">
                            <button
                                onClick={() => navigate("/cafe-management")}
                                className="px-4 md:px-6 py-2 border-2 border-[#bb8f70] text-[#402e32] rounded-3xl hover:bg-button1 hover:text-white hover:border-button1 transition-all duration-300 text-sm md:text-base font-medium"
                            >
                                انصراف
                            </button>
                            <button className="px-4 md:px-6 py-2 bg-button1 text-white rounded-3xl hover:bg-[#5f494f] transition-all duration-300 text-sm md:text-base font-medium">
                                تایید
                            </button>
                        </div>

                        {/* Basic Info */}
                        <div className="space-y-4">
                            <div>
                                <h2 className="font-bold text-lg text-[#402E32] mb-2">{cafeData.Name}</h2>
                                <div className="w-16 h-1 bg-[#80931e] rounded-full"></div>
                            </div>

                            <div className="flex items-center gap-3 text-[#402E32]">
                                <GrLocation className="text-lg flex-shrink-0" />
                                <span className="text-sm md:text-base">{cafeData.address || "آدرس موجود نیست"}</span>
                            </div>

                            <div className="flex items-center gap-3 text-[#402E32]">
                                <FaRegStar className="text-lg flex-shrink-0" />
                                <span className="text-sm md:text-base">{cafeData.rating || 0}</span>
                            </div>

                            <div>
                                <h3 className="font-bold text-[#402E32] mb-2">درباره کافه</h3>
                                <p className="text-sm md:text-base text-[#555]">
                                    {cafeData.description || "توضیحاتی برای این کافه وجود ندارد."}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Features Section */}
                <div className="mb-8">
                    <h2 className="font-bold text-[#402E32] mb-4 text-base md:text-lg">ویژگی ها</h2>
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                        {CAFE_FEATURES.map((feature, idx) => (
                            <div
                                key={idx}
                                className="bg-[#e1d5c2] p-4 rounded-2xl flex flex-col items-center gap-3 text-center transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md"
                            >
                                <img src={feature.icon} alt={feature.label} className="w-6 h-6" />
                                <span className="text-[#402E32] font-medium text-xs md:text-sm whitespace-normal">
                                    {feature.label}
                                </span>
                                {feature.value && (
                                    <span className="text-[#402E32] text-xs">{feature.value}</span>
                                )}
                            </div>
                        ))}
                        <button className="bg-[#5e5450] p-4 rounded-2xl flex items-center justify-center transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                            <img src={Vector9} alt="افزودن" className="w-6 h-6" />
                        </button>
                    </div>
                </div>

                {/* Categories Section */}
                <div className="mb-8">
                    <div className="flex items-center justify-between mb-4">
                        <h2 className="font-bold text-[#402E32] text-base md:text-lg">دسته‌بندی‌ها</h2>
                        <button
                            onClick={() => setIsEditMode(!isEditMode)}
                            className="flex items-center gap-2 text-button1 hover:text-[#5f494f] transition-colors"
                            title={isEditMode ? "خروج از حالت ویرایش" : "ویرایش دسته‌بندی‌ها"}
                        >
                            <img src={Vector16} alt="ویرایش" className="w-5 h-5" />
                            <span className="text-sm md:text-base">{isEditMode ? "تمام" : "ویرایش"}</span>
                        </button>
                    </div>

                    <div className="categories-scroll flex gap-3 md:gap-4 overflow-x-auto scrollbar-hide pb-2">
                        {categories.map((category, idx) => (
                            <div key={idx} className="flex-shrink-0">
                                {isEditMode && editingIndex === idx ? (
                                    <div className="flex flex-col gap-2">
                                        <div className="flex gap-1">
                                            <IoMdCheckmark
                                                onClick={handleSaveCategory}
                                                className="text-green-600 cursor-pointer hover:text-green-800 w-5 h-5"
                                                title="ذخیره"
                                            />
                                            <IoMdClose
                                                onClick={handleCancelEdit}
                                                className="text-red-600 cursor-pointer hover:text-red-800 w-5 h-5"
                                                title="لغو"
                                            />
                                        </div>
                                        <input
                                            type="text"
                                            value={editValue}
                                            onChange={(e) => setEditValue(e.target.value)}
                                            className="border-2 border-[#bb8f70] rounded-lg px-2 py-1 text-xs md:text-sm focus:outline-none focus:border-button1 min-w-[100px]"
                                            autoFocus
                                        />
                                    </div>
                                ) : (
                                    <div className={`flex items-center gap-2 px-3 py-2 rounded-lg text-[#402E32] text-xs md:text-sm whitespace-nowrap ${
                                        isEditMode
                                            ? "bg-gray-100 hover:bg-gray-200"
                                            : "bg-[#e1d5c2]"
                                    } transition-colors`}>
                                        <span>{category}</span>
                                        {isEditMode && (
                                            <>
                                                <BiEdit
                                                    onClick={() => handleEditCategory(idx)}
                                                    className="text-button1 cursor-pointer hover:text-[#5f494f] w-4 h-4 ml-1"
                                                    title="ویرایش"
                                                />
                                                <IoMdClose
                                                    onClick={() => handleDeleteCategory(idx)}
                                                    className="text-white bg-[#a79fa1] rounded cursor-pointer hover:bg-[#9a8f91] w-4 h-4"
                                                    title="حذف"
                                                />
                                            </>
                                        )}
                                    </div>
                                )}
                            </div>
                        ))}

                        {isEditMode && !isAddingCategory && (
                            <button
                                onClick={() => setIsAddingCategory(true)}
                                className="flex-shrink-0 text-button1 hover:text-[#5f494f] font-bold text-sm md:text-base transition-colors whitespace-nowrap"
                            >
                                + افزودن
                            </button>
                        )}

                        {isEditMode && isAddingCategory && (
                            <div className="flex-shrink-0 flex flex-col gap-2">
                                <div className="flex gap-1">
                                    <IoMdCheckmark
                                        onClick={handleAddCategory}
                                        className="text-green-600 cursor-pointer hover:text-green-800 w-5 h-5"
                                        title="ذخیره"
                                    />
                                    <IoMdClose
                                        onClick={() => {
                                            setIsAddingCategory(false);
                                            setNewCategory("");
                                        }}
                                        className="text-red-600 cursor-pointer hover:text-red-800 w-5 h-5"
                                        title="لغو"
                                    />
                                </div>
                                <input
                                    type="text"
                                    value={newCategory}
                                    onChange={(e) => setNewCategory(e.target.value)}
                                    placeholder="دسته جدید"
                                    className="border-2 border-[#bb8f70] rounded-lg px-2 py-1 text-xs md:text-sm focus:outline-none focus:border-button1 min-w-[100px]"
                                    autoFocus
                                />
                            </div>
                        )}
                    </div>
                </div>

                {/* Products Section */}
                <div>
                    <h2 className="font-bold text-[#402E32] mb-4 text-base md:text-lg">محصولات</h2>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6">
                        {CAFE_PRODUCTS.map((product, idx) => (
                            <div
                                key={idx}
                                className="bg-white border border-gray-200 rounded-xl p-4 transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md"
                            >
                                <h3 className="font-bold text-[#402E32] text-sm md:text-base mb-3">{product.name}</h3>
                                <img src={product.image} alt={product.name} className="w-full h-40 object-cover rounded-lg mb-3" />
                                <div className="flex justify-between items-center mb-3 text-sm">
                                    <span className="text-[#66585b]">قیمت:</span>
                                    <span className="font-medium text-[#402E32]">{product.price}</span>
                                </div>
                                <p className="text-xs md:text-sm text-[#66585b] line-clamp-3">
                                    {product.description}
                                </p>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </section>
    );
}
