import React, { useState, useEffect } from "react";
import { BiEdit } from "react-icons/bi";
import Vector9 from "../../assets/icons/Vector9.svg";
import Star1 from "../../assets/icons/Star1.svg";
import Group from "../../assets/icons/Group.svg";
import Pic1 from "../../assets/icons/pic1.svg";
import { Link } from "react-router-dom";
import cafeService from "../../services/cafe";

const CafeManagement = () => {
    const [cafes, setCafes] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {
        const fetchCafes = async () => {
            setLoading(true);
            setError("");

            try {
                const res = await cafeService.getCafeList();
                if (res.data.success && res.data.data) {
                    setCafes(res.data.data);
                    console.log("✅ Cafes loaded successfully:", res.data);
                } else {
                    setError("داده‌های دریافتی معتبر نیست");
                }
            } catch (error) {
                console.error("❌ Error loading cafes:", error);
                const errorMessage =
                    error.response?.data?.message ||
                    (error.request ? "خطا در برقراری ارتباط با سرور" : "خطای نامشخص رخ داده است");
                setError(errorMessage);
            } finally {
                setLoading(false);
            }
        };

        fetchCafes();
    }, []);

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

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

        if (cafes.length === 0) {
            return (
                <div className="text-center mt-20 text-gray-500">
                    هیچ کافه‌ای یافت نشد
                </div>
            );
        }

        return (
            <>
                {/* جدول دسکتاپ */}
                <div className="hidden lg:block mt-10 overflow-x-auto">
                    <table className="w-full border-collapse">
                        <thead>
                            <tr className="bg-[#EFEEEE]">
                                <th className="px-4 py-3 text-right text-[#402E32] font-medium text-sm">لوگو</th>
                                <th className="px-4 py-3 text-right text-[#402E32] font-medium text-sm">اسم</th>
                                <th className="px-4 py-3 text-right text-[#402E32] font-medium text-sm">آدرس</th>
                                <th className="px-4 py-3 text-right text-[#402E32] font-medium text-sm">ریتینگ</th>
                                <th className="px-4 py-3 text-right text-[#402E32] font-medium text-sm">ساعت کاری</th>
                                <th className="px-4 py-3 text-right text-[#402E32] font-medium text-sm">ادیت</th>
                            </tr>
                        </thead>
                        <tbody>
                            {cafes.map((cafe) => (
                                <tr key={cafe._id} className="border-b border-[#EFEEEE] hover:bg-gray-50 transition-colors">
                                    <td className="px-4 py-4 text-right">
                                        <img
                                            src={cafe.photo || Pic1}
                                            alt={cafe.Name}
                                            className="w-10 h-10 rounded-full object-cover"
                                        />
                                    </td>
                                    <td className="px-4 py-4 text-right text-[#402E32] font-medium text-sm whitespace-nowrap">
                                        {cafe.Name}
                                    </td>
                                    <td className="px-4 py-4 text-right text-[#402E32] text-sm max-w-xs overflow-hidden text-ellipsis">
                                        {cafe.address}
                                    </td>
                                    <td className="px-4 py-4 text-right">
                                        <div className="flex items-center gap-2">
                                            <img src={Star1} alt="rating" className="w-5 h-5" />
                                            <span className="text-[#402E32] text-sm">{cafe.rating || 0}</span>
                                        </div>
                                    </td>
                                    <td className="px-4 py-4 text-right">
                                        <div className="flex items-center gap-2">
                                            <img src={Group} alt="time" className="w-5 h-5" />
                                            <span className="text-[#402E32] text-sm whitespace-nowrap">
                                                {cafe.openinghour || "نامشخص"}
                                            </span>
                                        </div>
                                    </td>
                                    <td className="px-4 py-4 text-center">
                                        <Link
                                            to={`/edit-cafe/${cafe._id}`}
                                            className="inline-flex items-center justify-center gap-2 border-2 border-[#BB8F70] px-6 py-2 rounded-3xl text-sm font-light text-[#402E32] hover:bg-button1 hover:text-white hover:border-button1 transition-all duration-300"
                                        >
                                            <span>ادیت</span>
                                            <BiEdit className="w-4 h-4" />
                                        </Link>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>

                {/* کارت موبایل */}
                <div className="lg:hidden mt-6 space-y-4">
                    {cafes.map((cafe) => (
                        <div key={cafe._id} className="bg-white border-2 border-[#8b8886] rounded-xl p-4">
                            <div className="flex items-start gap-4 mb-4">
                                <img
                                    src={cafe.photo || Pic1}
                                    alt={cafe.Name}
                                    className="w-16 h-16 rounded-full object-cover flex-shrink-0"
                                />
                                <div className="flex-1 min-w-0">
                                    <h3 className="font-bold text-[#402E32] mb-1 text-sm">{cafe.Name}</h3>
                                    <p className="text-xs text-gray-600 truncate">{cafe.address}</p>
                                </div>
                            </div>

                            <div className="flex items-center justify-between mb-4 text-xs gap-4">
                                <div className="flex items-center gap-1">
                                    <img src={Star1} alt="rating" className="w-4 h-4" />
                                    <span className="text-[#402E32]">{cafe.rating || 0}</span>
                                </div>
                                <div className="flex items-center gap-1">
                                    <img src={Group} alt="time" className="w-4 h-4" />
                                    <span className="text-[#402E32]">{cafe.openinghour || "نامشخص"}</span>
                                </div>
                            </div>

                            <Link
                                to={`/edit-cafe/${cafe._id}`}
                                className="flex justify-center items-center gap-2 w-full border-2 border-[#BB8F70] py-2 rounded-full text-sm font-medium text-[#402E32] hover:bg-button1 hover:text-white hover:border-button1 transition-all duration-300"
                            >
                                <span>ادیت کافه</span>
                                <BiEdit className="w-4 h-4" />
                            </Link>
                        </div>
                    ))}
                </div>
            </>
        );
    };

    return (
        <section dir="rtl" className="w-full pt-24 max-w-full overflow-x-hidden">
            {/* بخش دکمه اضافه کردن */}
            <div className="flex items-center justify-between mb-8">
                <button className="flex items-center justify-center gap-3 px-6 py-3 bg-button1 text-white rounded-3xl text-sm lg:text-base font-medium hover:bg-amber-950 transition-all duration-300 cursor-pointer">
                    <span>افزودن شعبه جدید</span>
                    <img src={Vector9} alt="افزودن" className="w-5 h-5" />
                </button>
            </div>

            {/* عنوان */}
            <h1 className="text-[#402E32] font-bold text-lg lg:text-xl mb-6">کافه های شما</h1>

            {/* محتوای اصلی */}
            {renderContent()}
        </section>
    );
};

export default CafeManagement;