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";
import { FaRegEdit } from "react-icons/fa";
import EditCafeMenu from "./EditCafeMenu";
import { RxCross2 } from "react-icons/rx";
import { FiPlusSquare } from "react-icons/fi";
import { SlDislike } from "react-icons/sl";
import { SlLike } from "react-icons/sl";
import { RiDeleteBinLine } from "react-icons/ri";

// 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";
import coffee01 from "../../assets/image/coffee01.png";
import coffee07 from "../../assets/image/coffee07.png";
import coffee02 from "../../assets/image/coffee02.png";
import coffee03 from "../../assets/image/coffee03.png";
import coffee04 from "../../assets/image/coffee04.png";
import coffee05 from "../../assets/image/coffee05.png";
import coffee06 from "../../assets/image/coffee06.png";
import defaultuser from "../../assets/image/defaultuser.jpg";

// 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();
  const [editmenu, setEditMenu] = useState(false);

  // 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]);

  console.log("Editing cafe ID:", id);

  // API Calls
  const fetchCafeData = async () => {
    setLoading(true);
    setError("");
    try {
      const res = await cafeService.getCafeById(id);
      console.log("🔄 Fetching cafe data:", res?.data?.data);
      setCafeData(res?.data?.data);
    } 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">
      {editmenu ? (
        <EditCafeMenu setEditMenu={setEditMenu} />
      ) : (
        <>
          <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>

            <button
              onClick={() => setEditMenu(true)}
              className="flex items-center justify-center text-text1 gap-2 w-full h-14 border-4 border-border mb-14 rounded-4xl font-bold"
            >
              <FaRegEdit size={20} />
              ادیت منو کافه
            </button>

            {/* 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>

            {/* محتوا */}
            <div>
              <h3 className="font-bold text-text1">گالری تصاویر</h3>
              <div className="flex flex-cols-1 gap-3 mt-2">
                <div className="relative">
                  <img src={coffee01} alt="cofee" />
                  <span className=" flex justify-center items-center absolute top-0 left-0 text-white w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer">
                    <RxCross2 size={14} className=" hover:scale-120 " />
                  </span>
                </div>
                <div className="relative">
                  <img src={coffee02} alt="cofee" />
                  <span className=" flex justify-center items-center absolute top-0 left-0 text-white w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer">
                    <RxCross2 size={14} className=" hover:scale-120 " />
                  </span>
                </div>
                <div className="relative">
                  <img src={coffee03} alt="cofee" />
                  <span className=" flex justify-center items-center absolute top-0 left-0 text-white w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer">
                    <RxCross2 size={14} className=" hover:scale-120 " />
                  </span>
                </div>
              </div>

              <div className="flex flex-cols-1 gap-3 mt-3">
                <div className="relative">
                  <img src={coffee04} alt="cofee" />
                  <span className=" flex justify-center items-center absolute top-0 left-0 text-white w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer">
                    <RxCross2 size={14} className=" hover:scale-120 " />
                  </span>
                </div>
                <div className="relative">
                  <img src={coffee05} alt="cofee" />
                  <span className=" flex justify-center items-center absolute top-0 left-0 text-white w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer">
                    <RxCross2 size={14} className=" hover:scale-120 " />
                  </span>
                </div>
                <div className="relative">
                  <img src={coffee06} alt="cofee" />
                  <span className=" flex justify-center items-center absolute top-0 left-0 text-white w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer">
                    <RxCross2 size={14} className=" hover:scale-120 " />
                  </span>
                </div>
                <div className="relative">
                  <img src={coffee07} alt="coffee" className="block" />
                  <span
                    className="absolute top-1/2 left-1/2 
                   -translate-x-1/2 -translate-y-1/2
                   text-white cursor-pointer"
                  >
                    <FiPlusSquare size={24} />
                  </span>
                  <span
                    className="absolute top-0 left-0 
                   flex justify-center items-center
                   w-5 h-5 bg-[#938C8A] rounded-lg cursor-pointer"
                  >
                    <RxCross2 size={14} />
                  </span>
                </div>
              </div>
            </div>
            {/* کامنت */}

            <div className="mt-10 gap-2 ">
              <div>
                <h3 className="font-bold text-text1">کامنت ها </h3>
              </div>
              <div className=" flex-col   bg-[#EFEEEE] flex mt-5 rounded-2xl overflow-hidden p-3 ">
                <div className=" w-full flex justify-center ">
                  <img
                    className="w-20 h-20"
                    src={defaultuser}
                    alt="defaultuser"
                  />
                  <div className=" w-full mr-4 flex flex-col gap-3 ">
                    <div className="w-full flex justify-between ">
                      <h4 font-semibold text-text1>
                        روزبه سام
                      </h4>
                      <p className="text-sm">2مهر</p>
                    </div>
                    <p className=" text-[#66585B]  ">
                      فضای خیلی دنج و آرومی داشت، قهوه ترک‌ش فوق‌العاده بود 👌
                      دوباره حتما میام.
                    </p>
                  </div>
                </div>
                <div className="self-end  pl-2 flex gap-2 mt-2.5 ">
                  <span className="text-text1 text-sm font-semibold">پاسخ</span>
                  <RiDeleteBinLine className="ml-2" />
                  <SlLike />
                  <SlDislike />
                </div>
              </div>
              <div className=" flex-col   bg-[#EFEEEE] flex mt-5 rounded-2xl overflow-hidden p-3 ">
                <div className=" w-full flex justify-center ">
                  <img
                    className="w-20 h-20"
                    src={defaultuser}
                    alt="defaultuser"
                  />
                  <div className=" w-full mr-4 flex flex-col gap-3 ">
                    <div className="w-full flex justify-between ">
                      <h4 font-bold text-text1>
                        بهروز کمالی
                      </h4>
                      <p className="text-sm">17شهریور</p>
                    </div>
                    <p className=" text-[#66585B]  ">
                      مناسب قرار کاری بود، اینترنت خوب و صندلی راحت. حتما
                      پیشنهاد می‌کنم. برخورد پرسنل عالی بود، منو هم متنوع بود.
                      مخصوصاً کیک هویج‌شون حرف نداشت! جای پارک سخت پیدا شد،
                      مخصوصاً آخر هفته‌ها. مناسب قرار کاری بود، اینترنت خوب و
                      صندلی راحت. حتما پیشنهاد می‌کنم. برخورد پرسنل عالی بود،
                      منو هم متنوع بود.
                    </p>
                  </div>
                </div>
                <div className="self-end  pl-2 flex gap-2 mt-2.5 ">
                  <span className="text-text1 text-sm font-semibold">پاسخ</span>
                  <RiDeleteBinLine className="ml-2" />
                  <SlLike />
                  <SlDislike />
                </div>
              </div>
              <div className=" flex-col   bg-[#EFEEEE] flex mt-5 rounded-2xl overflow-hidden p-3 ">
                <div className=" w-full flex justify-center ">
                  <img
                    className="w-20 h-20"
                    src={defaultuser}
                    alt="defaultuser"
                  />
                  <div className=" w-full mr-4 flex flex-col gap-3 ">
                    <div className="w-full flex justify-between ">
                      <h4 font-semibold text-text1>
                        سحر فلاح
                      </h4>
                      <p className="text-sm">5شهریور</p>
                    </div>
                    <p className=" text-[#66585B]  ">
                      فضا قشنگ بود ولی سرویس‌دهی یکم طول کشید. امیدوارم دفعه بعد
                      سریع‌تر باشن. قیمت‌ها نسبت به کیفیت قابل قبوله، فقط موسیقی
                      پس‌زمینه یکم بلند بود.
                    </p>
                  </div>
                </div>
                <div className="self-end  pl-2 flex gap-2 mt-2.5 ">
                  <span className="text-text1 text-sm font-semibold">پاسخ</span>
                  <RiDeleteBinLine className="ml-2" />
                  <SlLike />
                  <SlDislike />
                </div>
              </div>
              <div className="flex justify-between mt-8">
                <p>29 دیدگاه</p>{" "}
                <p className="font-bold text-text1">مشاهده بیشتر</p>{" "}
              </div>
            </div>
          </div>
        </>
      )}
    </section>
  );
}
