import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import Bg1 from "../../assets/icons/bg1.svg";
import { GrLocation } from "react-icons/gr";
import { BiEdit } from "react-icons/bi";
import { FaRegStar } from "react-icons/fa";
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 Vector9 from "../../assets/icons/Vector9.svg";
import Vector16 from "../../assets/icons/Vector16.svg";
import Sperso from "../../assets/icons/sperso.svg";
import Coffee2 from "../../assets/icons/coffee2.svg";
import Coffee1 from "../../assets/icons/coffee1.svg";
import Coffee3 from "../../assets/icons/coffee3.svg";
import Edit from "../../assets/icons/edit.svg";
import { IoMdCheckmark, IoMdClose } from "react-icons/io";
import cafeService from "../../services/cafe";

export default function EditCafe() {
    const { id } = useParams();
    const navigate = useNavigate();
    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) : [
            "نوشیدنی سرد",
            "نوشیدنی گرم",
            "کیک و دسر",
            "صبحانه",
            "ساندویچ و برگر",
            "سالاد و پیش غذا",
        ];
    });

    const [isEditMode, setIsEditMode] = useState(false);
    const [isAdding, setIsAdding] = useState(false);
    const [newCategory, setNewCategory] = useState("");
    const [editingIndex, setEditingIndex] = useState(null);
    const [editValue, setEditValue] = useState("");

    // دریافت اطلاعات کافه
    useEffect(() => {
        const getCafeData = 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);
                if (error.response) {
                    setError(error.response.data.message || "خطا در دریافت اطلاعات کافه");
                } else if (error.request) {
                    setError("خطا در برقراری ارتباط با سرور");
                } else {
                    setError("خطای نامشخص رخ داده است");
                }
            } finally {
                setLoading(false);
            }
        };

        if (id) {
            getCafeData();
        }
    }, [id]);

    // ذخیره دسته‌بندی‌ها در localStorage
    useEffect(() => {
        localStorage.setItem('cafeCategories', JSON.stringify(categories));
    }, [categories]);

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

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

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

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

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

    if (loading) {
        return (
            <div className="flex justify-center items-center h-screen">
                <div className="text-[#7F4629] 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 (
            <>
                <style>
                    {`
                    .scrollbar-hide::-webkit-scrollbar {
                        display: none;
                    }
                    .scrollbar-hide {
                        -ms-overflow-style: none;
                        scrollbar-width: none;
                    }
                    body::-webkit-scrollbar {
                        display: none;
                    }
                    body {
                        -ms-overflow-style: none;
                        scrollbar-width: none;
                    }
                `}
                </style>
                <section dir="rtl" className="lg:-mt-12">
                    <h3 className="text-[#402E32] font-bold mb-4 lg:mb-0">ادیت {cafeData.Name}</h3>

                    <div className="mt-4 lg:mt-9 border-2 border-[#8b8886] p-4 lg:p-10 rounded-2xl flex flex-col lg:flex-row gap-4">
                        <div className="w-full lg:w-auto">
                            <img className="w-full lg:w-[461px] rounded-lg" src={cafeData.photo || Bg1} alt="Logo" />
                        </div>

                        <div className="relative flex flex-col gap-4 lg:gap-4.5 w-full">
                            <div className="flex gap-2 justify-end lg:absolute lg:top-2 lg:left-0 lg:-mt-5">
                                <button
                                    onClick={() => navigate('/cafe-management')}
                                    className="border-2 border-[#bb8f70] w-20 lg:w-25 h-10 rounded-3xl text-sm lg:text-base text-[#402e32] hover:bg-[#7f4629] hover:text-white transition-all duration-300 hover:border-none">
                                    انصراف
                                </button>
                                <button
                                    className="border-2 border-[#bb8f70] bg-[#7f4629] text-white w-20 lg:w-25 h-10 rounded-3xl text-sm lg:text-base hover:bg-[#5f494f] transition-all duration-300 hover:border-none">
                                    تایید
                                </button>
                            </div>

                            <BiEdit className="w-5 h-5 mt-0 lg:-mt-1" />
                            <h3 className="font-bold text-base">{cafeData.Name}</h3>
                            <hr className="w-full lg:w-38 -mt-3 border-1 text-[#80931e]" />

                            <div className="flex items-center gap-2">
                                <GrLocation />
                                <span className="text-sm lg:text-base">{cafeData.address || "آدرس موجود نیست"}</span>
                            </div>
                            <hr className="w-full lg:w-38 -mt-3 border-1 text-[#80931e]" />

                            <div className="flex items-center gap-2">
                                <FaRegStar />
                                <span className="text-sm lg:text-base">{cafeData.rating || 0}</span>
                            </div>

                            <h3 className="font-bold text-base">درباره کافه</h3>
                            <span className="text-sm lg:text-base">
                                {cafeData.description || "توضیحاتی برای این کافه وجود ندارد."}
                            </span>
                            <hr className="w-full lg:w-[104%] -mt-3 border-1 text-[#80931e]" />

                            <h3 className="text-[#402E32] font-bold mt-6 lg:mt-10 lg:relative lg:-right-64">
                                ویژگی ها
                            </h3>

                            <div className="grid grid-cols-2 sm:grid-cols-3 lg:flex lg:relative lg:-mr-71 lg:-ml-7 mt-5 gap-3">
                                <div
                                    className="bg-[#e1d5c2] w-full lg:w-[140px] h-[137.6px] flex flex-col items-center gap-4 lg:gap-8 text-center rounded-2xl lg:rounded-4xl transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Coffee3} className="w-6 h-6 text-[#402E32] mt-5" />
                                    <span className="text-[#402E32] font-medium text-sm lg:text-base whitespace-nowrap px-2">
                                        منو کافه:
                                    </span>
                                </div>

                                <div
                                    className="flex flex-col gap-3 lg:gap-4 text-[#402E32] font-medium w-full lg:w-[161.5px] h-[137.6px] bg-[#e1d5c2] rounded-2xl lg:rounded-4xl pr-3 text-sm lg:text-base transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Vector15} className="w-6 h-6 text-[#402E32] mt-5" />
                                    <span>ساعت کاری:</span>
                                    <span> 23 - 8</span>
                                </div>

                                <div
                                    className="flex flex-col gap-3 lg:gap-4 text-[#402E32] font-medium w-full lg:w-[161.5px] h-[137.6px] bg-[#e1d5c2] rounded-2xl lg:rounded-4xl pr-3 text-sm lg:text-base transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Vector14} className="w-6 h-6 text-[#402E32] mt-5" />
                                    <span>رزرو :</span>
                                    <span>رزرو آنلاین</span>
                                </div>

                                <div
                                    className="flex flex-col gap-3 lg:gap-4 text-[#402E32] font-medium w-full lg:w-[170.5px] h-[137.6px] bg-[#e1d5c2] rounded-2xl lg:rounded-4xl pr-3 text-sm lg:text-base transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Vector11} className="w-6 h-6 text-[#402E32] mt-5" />
                                    <span>موسیقی :</span>
                                    <span>موسیقی زنده آخر هفته</span>
                                </div>

                                <div
                                    className="flex flex-col gap-3 lg:gap-4 text-[#402E32] font-medium w-full lg:w-[161.5px] h-[137.6px] bg-[#e1d5c2] rounded-2xl lg:rounded-4xl pr-3 text-sm lg:text-base transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Vector13} className="w-6 h-6 text-[#402E32] mt-5" />
                                    <span>پارکینگ :</span>
                                    <span>عمومی</span>
                                </div>

                                <div
                                    className="flex flex-col gap-3 lg:gap-4 text-[#402E32] font-medium w-full lg:w-[161.5px] h-[137.6px] bg-[#e1d5c2] rounded-2xl lg:rounded-4xl pr-3 text-sm lg:text-base transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Vector12} className="w-6 h-6 text-[#402E32] mt-5" />
                                    <span>دسترسی آسان :</span>
                                    <span>مناسب افراد ناتوان</span>
                                </div>

                                <div
                                    className="flex justify-center items-center w-full lg:w-[150.5px] h-[137.6px] bg-[#5e5450] rounded-2xl lg:rounded-4xl transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                    <img src={Vector9} className="w-6 h-6 text-[#402E32]" />
                                </div>
                            </div>

                            <div>
                                <div className="mt-10 lg:-mr-64 text-[#402E32] font-medium w-full lg:w-[132%]">
                                    <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
                                        <div className="w-full sm:max-w-[930px] overflow-hidden flex-1">
                                            <div className="categories-scroll flex gap-6 lg:gap-10 overflow-x-auto scrollbar-hide">
                                                <div className="flex items-center gap-2 justify-center flex-shrink-0">
                                                    <img
                                                        src={Vector16}
                                                        alt="Logo"
                                                        className="cursor-pointer hover:opacity-70 transition-opacity"
                                                        onClick={() => setIsEditMode(!isEditMode)}
                                                        title={isEditMode ? "خروج از حالت ویرایش" : "ویرایش عنوان‌ها"}
                                                    />
                                                    <span className="whitespace-nowrap text-sm lg:text-base">عنوان</span>
                                                </div>

                                                {!isEditMode ? (
                                                    <>
                                                        {categories.map((category, index) => (
                                                            <span key={index} className="whitespace-nowrap flex-shrink-0 text-sm lg:text-base">{category}</span>
                                                        ))}
                                                    </>
                                                ) : (
                                                    <>
                                                        {categories.map((category, index) => (
                                                            <div key={index} className="flex flex-col items-center gap-1 flex-shrink-0">
                                                                {editingIndex === index ? (
                                                                    <>
                                                                        <div className="flex items-center gap-1 mb-1">
                                                                            <IoMdCheckmark
                                                                                className="text-green-600 cursor-pointer hover:text-green-800 w-4 h-4 flex-shrink-0"
                                                                                onClick={handleSaveEdit}
                                                                                title="ذخیره"
                                                                            />
                                                                            <IoMdClose
                                                                                className="text-red-600 cursor-pointer hover:text-red-800 w-4 h-4 flex-shrink-0"
                                                                                onClick={handleCancelEdit}
                                                                                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-sm focus:outline-none focus:border-[#7f4629] w-[100px] text-center"
                                                                            autoFocus
                                                                        />
                                                                    </>
                                                                ) : (
                                                                    <>
                                                                        <div className="flex items-center gap-2">
                                                                            <BiEdit
                                                                                className="text-[#7f4629] cursor-pointer hover:text-[#5f494f] w-5 h-5 flex-shrink-0"
                                                                                onClick={() => handleStartEdit(index)}
                                                                                title="ویرایش"
                                                                            />
                                                                            <span className="whitespace-nowrap text-sm lg:text-base">{category}</span>
                                                                            <IoMdClose
                                                                                className="text-white bg-[#a79fa1] rounded-md cursor-pointer size-5 flex-shrink-0"
                                                                                onClick={() => handleDeleteCategory(index)}
                                                                                title="حذف"
                                                                            />
                                                                        </div>
                                                                    </>
                                                                )}
                                                            </div>
                                                        ))}
                                                    </>
                                                )}
                                            </div>
                                        </div>

                                        {isEditMode && (
                                            <div className="flex-shrink-0 w-full sm:w-auto" style={{ minWidth: '120px' }}>
                                                {!isAdding ? (
                                                    <button
                                                        onClick={() => setIsAdding(true)}
                                                        className="text-[#7f4629] hover:text-[#5f494f] font-bold transition-colors whitespace-nowrap w-full text-sm lg:text-base"
                                                        title="اضافه کردن عنوان جدید"
                                                    >
                                                        + افزودن
                                                    </button>
                                                ) : (
                                                    <div className="flex flex-col items-center gap-1">
                                                        <div className="flex items-center gap-1 mb-1">
                                                            <IoMdCheckmark
                                                                className="text-green-600 cursor-pointer hover:text-green-800 w-4 h-4 flex-shrink-0"
                                                                onClick={handleAddCategory}
                                                                title="ذخیره"
                                                            />
                                                            <IoMdClose
                                                                className="text-white bg-[#a79fa1] rounded-md cursor-pointer w-4 h-4 flex-shrink-0"
                                                                onClick={() => {
                                                                    setIsAdding(false);
                                                                    setNewCategory("");
                                                                }}
                                                                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-sm focus:outline-none focus:border-[#7f4629] w-[100px] text-center"
                                                            autoFocus
                                                        />
                                                    </div>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <hr className="w-full lg:w-[132%] lg:-mr-66 mt-3 border-2 rounded-3xl text-[#939393]" />

                                <div className="mt-9 flex items-center gap-2 lg:-mr-64 text-[#a79fa1] font-bold text-sm lg:text-base">
                                    <img src={Vector16} alt="Logo" />
                                    <h3>افزودن زیر عنوان</h3>
                                </div>

                                <div className="mt-9 flex items-center gap-2 lg:-mr-64 text-[#66585b] font-bold text-sm lg:text-base">
                                    <img className="w-5.5 h-5.5" src={Edit} alt="Logo" />
                                    <img className="w-6 h-6" src={Coffee3} alt="Logo" />
                                    <h3>قهوه ها</h3>
                                    <hr className="mt-9 -mr-15 w-[5%] border-1 text-[#80931e] hidden lg:block" />
                                </div>

                                <div className="mt-9 flex items-center gap-2 lg:-mr-64 text-[#66585b] font-bold text-sm lg:text-base">
                                    <img src={Vector16} alt="Logo" />
                                    <h3>آیتم</h3>
                                </div>

                                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 lg:-mr-64">
                                    <div
                                        className="mt-8 lg:mt-13 flex items-center flex-col justify-center w-full lg:w-[320px] h-[391px] transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                        <h1 className="text-[#402E32] font-bold text-sm lg:text-base lg:-mr-50">اسپرسو100%</h1>
                                        <img src={Sperso} alt="Logo" className="mt-5" />
                                        <div className="flex justify-between gap-20 lg:gap-50 mt-3 text-[#66585b] font-medium text-sm lg:text-base">
                                            <span>قیمت</span>
                                            <span>118.000</span>
                                        </div>
                                        <span className="font-light text-[#66585b] mt-2 break-words px-4 lg:mr-4 text-xs lg:text-[14.90px]">
                                            45 میلی لیتر، قهوه، 100% عربیکا، دم شده با دستگاه اسپرسو ساز،
                                            به همراه یک عدد آب معدنی مینی
                                        </span>
                                        <hr className="mt-5 w-[90%] border-3 rounded-4xl text-[#e6e2de]" />
                                    </div>

                                    <div
                                        className="mt-8 lg:mt-10 flex items-center flex-col justify-center w-full lg:w-[320px] h-[391px] transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                        <h1 className="text-[#402E32] font-bold text-sm lg:text-base lg:-mr-50">
                                            کارامل ماکیاتو
                                        </h1>
                                        <img src={Coffee1} alt="Logo" className="mt-5" />
                                        <div className="flex justify-between gap-20 lg:gap-50 mt-3 text-[#66585b] font-medium text-sm lg:text-base">
                                            <span>قیمت</span>
                                            <span>149.000</span>
                                        </div>
                                        <span className="font-light text-[#66585b] mt-2 break-words px-4 lg:mr-4 text-xs lg:text-[14.90px]">
                                            220 میلی لیتر، 2 شات اسپرسو 30% روبوستا، 70% عربیکا، یک لکه
                                            فوم شیر، سیروپ کارامل
                                        </span>
                                        <hr className="mt-5 w-[90%] border-3 rounded-4xl text-[#e6e2de]" />
                                    </div>

                                    <div
                                        className="mt-8 lg:mt-10 flex items-center flex-col justify-center w-full lg:w-[320px] h-[391px] transform hover:-translate-y-1 transition-all duration-300 hover:shadow-md">
                                        <h1 className="text-[#402E32] font-bold text-sm lg:text-base lg:-mr-47">
                                            اسپرسو آفوگاتو
                                        </h1>
                                        <img src={Coffee2} alt="Logo" className="mt-5" />
                                        <div className="flex justify-between gap-20 lg:gap-50 mt-3 text-[#66585b] font-medium text-sm lg:text-base">
                                            <span>قیمت</span>
                                            <span>118.000</span>
                                        </div>
                                        <span
                                            className="font-light text-[#66585b] mt-2 mb-10 break-words px-4 lg:-mr-23 text-xs lg:text-[14.90px]">
                                            اسپرسو، یک اسکوپ بستنی وانیلی
                                        </span>
                                        <hr className="w-[90%] border-3 rounded-4xl text-[#e6e2de]" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            </>
        );
    }
