// src/pages/Academies.js
import React, { useState, useEffect, useCallback } from "react";
import toast from "react-hot-toast";
import {
  getAcademies,
  updateAcademyStatus,
  deleteAcademy,
  getAcademyStats
} from "../../components/adminApi";  // اصلاح مسیر
import Layout from "../../components/academy/Layout";
import { FaSearch, FaEdit, FaTrash, FaEye, FaStar, FaUniversity, FaTimes } from "react-icons/fa";
import { ImageBaseUrl } from "../../components/BaseUrl";

// در صورت نیاز به BASE_URL
const IMAGE_BASE_URL = ImageBaseUrl|| "";

const Academies = () => {
  const [academies, setAcademies] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [search, setSearch] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [showModal, setShowModal] = useState(false);
  const [selectedAcademy, setSelectedAcademy] = useState(null);

  const fetchAcademies = useCallback(async () => {
    setLoading(true);
    try {
      const response = await getAcademies({ page, limit: 12, search });
      console.log("Academies response:", response.data);
      
      if (response.data.success) {
        const responseData = response.data.data;
        setAcademies(responseData?.academies || []);
        setStats(responseData?.stats || null);
        setTotalPages(responseData?.pagination?.totalPages || 1);
      } else {
        toast.error(response.data.message || "خطا در دریافت آکادمی‌ها");
      }
    } catch (error) {
      console.error("Error fetching academies:", error);
      toast.error("خطا در دریافت آکادمی‌ها");
    } finally {
      setLoading(false);
    }
  }, [page, search]);

  const fetchStats = async () => {
    try {
      const response = await getAcademyStats();
      console.log("Stats response:", response.data);
      
      if (response.data.success) {
        setStats(response.data.data);
      }
    } catch (error) {
      console.error("Error fetching stats:", error);
    }
  };

  useEffect(() => {
    fetchAcademies();
    fetchStats();
  }, [fetchAcademies]);

  const handleStatusChange = async (academyId, status) => {
    try {
      const response = await updateAcademyStatus({ academyId, status });
      if (response.data.success) {
        toast.success("وضعیت آکادمی تغییر کرد");
        fetchAcademies();
        fetchStats();
      } else {
        toast.error(response.data.message || "خطا در تغییر وضعیت");
      }
    } catch (error) {
      console.error("Error updating status:", error);
      toast.error("خطا در تغییر وضعیت");
    }
  };

  const handleDelete = async (academyId) => {
    if (window.confirm("آیا از حذف این آکادمی مطمئن هستید؟\nتوجه: با حذف آکادمی، تمام دوره‌های آن نیز حذف خواهند شد.")) {
      try {
        const response = await deleteAcademy(academyId);
        if (response.data.success) {
          toast.success("آکادمی حذف شد");
          fetchAcademies();
          fetchStats();
        } else {
          toast.error(response.data.message || "خطا در حذف آکادمی");
        }
      } catch (error) {
        console.error("Error deleting academy:", error);
        toast.error("خطا در حذف آکادمی");
      }
    }
  };

  const handleSearch = (e) => {
    e.preventDefault();
    setSearch(searchInput);
    setPage(1);
  };

  const handleClearSearch = () => {
    setSearchInput("");
    setSearch("");
    setPage(1);
  };

  const getImageUrl = (imagePath) => {
    if (!imagePath) return null;
    if (imagePath.startsWith("http")) return imagePath;
    return `${IMAGE_BASE_URL}${imagePath}`;
  };

  const getStatusText = (status) => {
    const statusMap = {
      active: { text: "فعال", className: "bg-green-100 text-green-700" },
      inactive: { text: "غیرفعال", className: "bg-gray-100 text-gray-700" },
      blocked: { text: "مسدود", className: "bg-red-100 text-red-700" }
    };
    return statusMap[status] || { text: status || "فعال", className: "bg-gray-100 text-gray-700" };
  };

  
  

  if (loading && page === 1) {
    return (
      <Layout>
        <div className="flex justify-center items-center h-96">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-pink-500"></div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="p-6">
        <div className="mb-6">
          <h1 className="text-2xl font-bold">مدیریت آکادمی‌ها</h1>
          <p className="text-gray-500 mt-1">لیست تمام آکادمی‌های ثبت شده در سامانه</p>
        </div>

        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div className="bg-gradient-to-r from-purple-500 to-purple-600 rounded-lg p-4 text-white">
              <div className="flex justify-between items-center">
                <div>
                  <p className="text-sm opacity-90">تعداد آکادمی‌ها</p>
                  <p className="text-3xl font-bold">{stats.totalAcademies?.toLocaleString() || 0}</p>
                </div>
                <FaUniversity className="text-4xl opacity-50" />
              </div>
            </div>
            <div className="bg-white rounded-lg p-4 shadow-sm">
              <p className="text-gray-500 text-sm">میانگین امتیاز</p>
              <p className="text-2xl font-bold text-yellow-500">{stats.avgRate?.toFixed(1) || 0}</p>
            </div>
            <div className="bg-white rounded-lg p-4 shadow-sm">
              <p className="text-gray-500 text-sm">مجموع امتیاز</p>
              <p className="text-2xl font-bold">{stats.totalRate?.toLocaleString() || 0}</p>
            </div>
          </div>
        )}

        {/* Search */}
        <form onSubmit={handleSearch} className="mb-6">
          <div className="relative">
            <input
              type="text"
              placeholder="جستجوی آکادمی..."
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              className="w-full px-4 py-3 pl-12 pr-4 border rounded-xl focus:outline-none focus:ring-2 focus:ring-pink-500"
            />
            <FaSearch className="absolute left-4 top-3.5 text-gray-400" />
            {searchInput && (
              <button
                type="button"
                onClick={handleClearSearch}
                className="absolute left-12 top-3.5 text-gray-400 hover:text-gray-600"
              >
                <FaTimes />
              </button>
            )}
          </div>
        </form>

        {/* Search result info */}
        {search && (
          <div className="mb-4 text-sm text-gray-500">
            نتایج جستجو برای: <span className="font-semibold">{search}</span>
            <button
              onClick={handleClearSearch}
              className="mr-2 text-pink-500 hover:text-pink-600"
            >
              (پاک کردن)
            </button>
          </div>
        )}

        {/* Academies Grid */}
        {academies.length === 0 && !loading ? (
          <div className="text-center py-12 bg-gray-50 rounded-xl">
            <FaUniversity className="text-6xl text-gray-300 mx-auto mb-4" />
            <p className="text-gray-500">آکادمی‌ای یافت نشد</p>
            {search && (
              <button
                onClick={handleClearSearch}
                className="mt-4 text-pink-500 hover:text-pink-600"
              >
                پاک کردن جستجو
              </button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {academies.map((academy) => {
              const statusInfo = getStatusText(academy.status);
              return (
                <div
                  key={academy._id}
                  className="bg-white rounded-xl shadow-md overflow-hidden hover:shadow-lg transition-all hover:-translate-y-1"
                >
                  <div className="relative h-32 bg-gradient-to-r from-pink-500 to-purple-500">
                    <div className="absolute top-2 left-2">
                      <span className={`px-2 py-1 rounded text-xs font-medium ${statusInfo.className}`}>
                        {statusInfo.text}
                      </span>
                    </div>
                    <div className="absolute -bottom-8 right-4">
                      <div className="w-16 h-16 rounded-full bg-white p-1 shadow-lg">
                        <div className="w-full h-full rounded-full overflow-hidden bg-gray-200">
                          {academy.academy_image ? (
                            <img 
                              src={getImageUrl(academy.academy_image)} 
                              alt={academy.academy_name}
                              className="w-full h-full object-cover" 
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center text-gray-400">
                              <FaUniversity />
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="pt-10 p-4">
                    <div className="flex justify-between items-start">
                      <div>
                        <h3 className="font-bold text-lg line-clamp-1">{academy.academy_name}</h3>
                        <p className="text-sm text-gray-500 mt-1">مدیر: {academy.userId?.user_name || "نامشخص"}</p>
                      </div>
                      <div className="flex items-center gap-1 bg-yellow-100 px-2 py-1 rounded-lg">
                        <FaStar className="text-yellow-500 text-sm" />
                        <span className="text-sm font-bold">{academy.rate || 0}</span>
                      </div>
                    </div>

                    <p className="text-sm text-gray-600 mt-2 line-clamp-2">
                      {academy.bio || "توضیحاتی ثبت نشده"}
                    </p>

                    <div className="flex justify-between items-center mt-4 pt-3 border-t">
                      <div className="flex gap-2">
                        <button
                          onClick={() => {
                            setSelectedAcademy(academy);
                            setShowModal(true);
                          }}
                          className="p-2 text-blue-500 hover:bg-blue-50 rounded-lg transition"
                          title="جزئیات"
                        >
                          <FaEye />
                        </button>
                        <button
                          onClick={() => handleDelete(academy._id)}
                          className="p-2 text-red-500 hover:bg-red-50 rounded-lg transition"
                          title="حذف آکادمی"
                        >
                          <FaTrash />
                        </button>
                      </div>
                      {/* <select
                        value={academy.status || "active"}
                        onChange={(e) => handleStatusChange(academy._id, e.target.value)}
                        className="text-xs px-2 py-1 border rounded-lg focus:outline-none focus:ring-1 focus:ring-pink-500"
                      >
                        <option value="active">فعال</option>
                        <option value="inactive">غیرفعال</option>
                        <option value="blocked">مسدود</option>
                      </select> */}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex justify-center gap-2 mt-6">
            <button
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page === 1}
              className="px-4 py-2 border rounded-lg disabled:opacity-50 hover:bg-gray-50 transition"
            >
              قبلی
            </button>
            <span className="px-4 py-2">
              صفحه {page} از {totalPages}
            </span>
            <button
              onClick={() => setPage(p => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="px-4 py-2 border rounded-lg disabled:opacity-50 hover:bg-gray-50 transition"
            >
              بعدی
            </button>
          </div>
        )}

        {/* Modal */}
        {showModal && selectedAcademy && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white rounded-xl max-w-md w-full mx-4 max-h-[85vh] overflow-y-auto">
              <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white">
                <h3 className="text-lg font-bold">جزئیات آکادمی</h3>
                <button 
                  onClick={() => setShowModal(false)} 
                  className="text-gray-500 hover:text-gray-700 transition"
                >
                  <FaTimes />
                </button>
              </div>
              <div className="p-4 space-y-3">
                <div className="flex justify-center">
                  <div className="w-24 h-24 rounded-full overflow-hidden bg-gray-200 shadow-md">
                    {selectedAcademy.academy_image ? (
                      <img 
                        src={getImageUrl(selectedAcademy.academy_image)} 
                        alt={selectedAcademy.academy_name}
                        className="w-full h-full object-cover" 
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-gray-400 text-3xl">
                        <FaUniversity />
                      </div>
                    )}
                  </div>
                </div>
                
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">نام آکادمی:</span>
                  <span className="font-medium">{selectedAcademy.academy_name}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">مدیر:</span>
                  <span>{selectedAcademy.userId?.user_name || "-"}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">ایمیل:</span>
                  <span className="text-sm">{selectedAcademy.userId?.email || "-"}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">امتیاز:</span>
                  <span className="text-yellow-500 font-bold">{selectedAcademy.rate || 0}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">تعداد نظرات:</span>
                  <span>{selectedAcademy.number_of_rate || 0}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">شماره شبا:</span>
                  <span className="font-mono text-sm">{selectedAcademy.sheba || "ثبت نشده"}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">تاریخ ثبت:</span>
                  <span>{new Date(selectedAcademy.createdAt).toLocaleDateString("fa-IR")}</span>
                </div>
                <div className="border-t pt-3">
                  <p className="text-gray-500 mb-1">درباره:</p>
                  <p className="text-sm leading-relaxed">{selectedAcademy.bio || "توضیحاتی ثبت نشده"}</p>
                </div>
              </div>
              <div className="p-4 border-t flex justify-end">
                <button
                  onClick={() => setShowModal(false)}
                  className="px-4 py-2 bg-gray-200 rounded-lg hover:bg-gray-300 transition"
                >
                  بستن
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </Layout>
  );
};

export default Academies;