// src/pages/Purchased.js
import React, { useState, useEffect, useCallback } from "react";
import toast from "react-hot-toast";
import { getPurchasedCourses, getPurchasedStats } from "../../components/adminApi";  // اصلاح مسیر
import Layout from "../../components/academy/Layout";
import { FaSearch, FaUser, FaBook, FaCalendar, FaEye, FaTimes } from "react-icons/fa";

const Purchased = () => {
  const [purchases, setPurchases] = 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 [selectedPurchase, setSelectedPurchase] = useState(null);
  const [showModal, setShowModal] = useState(false);

  const fetchPurchases = useCallback(async () => {
    setLoading(true);
    try {
      const response = await getPurchasedCourses({ page, limit: 15, search });
      console.log("Purchased response:", response.data);
      
      if (response.data.success) {
        const responseData = response.data.data;
        setPurchases(responseData?.purchases || []);
        setStats(responseData?.stats || null);
        setTotalPages(responseData?.pagination?.totalPages || 1);
      } else {
        toast.error(response.data.message || "خطا در دریافت اطلاعات");
      }
    } catch (error) {
      console.error("Error fetching purchases:", error);
      toast.error("خطا در دریافت اطلاعات");
    } finally {
      setLoading(false);
    }
  }, [page, search]);

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

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

  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;
    // اگر نیاز به BASE_URL داری، اینجا اضافه کن
    return imagePath;
  };

  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-2 gap-4 mb-6">
            <div className="bg-gradient-to-r from-green-500 to-green-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.totalPurchases?.toLocaleString() || 0}</p>
                </div>
                <FaBook className="text-4xl opacity-50" />
              </div>
            </div>
            <div className="bg-gradient-to-r from-blue-500 to-blue-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.uniqueUsers?.toLocaleString() || 0}</p>
                </div>
                <FaUser className="text-4xl opacity-50" />
              </div>
            </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>
        )}

        {/* Purchases List */}
        <div className="space-y-4">
          {purchases.length === 0 && !loading ? (
            <div className="text-center py-12 bg-gray-50 rounded-xl">
              <FaBook 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>
          ) : (
            purchases.map((purchase) => (
              <div
                key={purchase._id}
                className="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition-all hover:-translate-y-1"
              >
                <div className="flex flex-col md:flex-row justify-between gap-4">
                  <div className="flex-1">
                    <div className="flex items-start gap-3">
                      <div className="w-14 h-14 rounded-lg bg-gray-100 flex items-center justify-center overflow-hidden flex-shrink-0">
                        {purchase.course_id?.course_image ? (
                          <img 
                            src={getImageUrl(purchase.course_id.course_image)} 
                            alt={purchase.course_id?.cuorse_name}
                            className="w-full h-full object-cover" 
                          />
                        ) : (
                          <FaBook className="text-gray-400 text-2xl" />
                        )}
                      </div>
                      <div>
                        <h3 className="font-bold text-lg">{purchase.course_id?.cuorse_name || "نامشخص"}</h3>
                        <p className="text-sm text-gray-500">مدرس: {purchase.course_id?.teacher_name || "نامشخص"}</p>
                        <div className="flex flex-wrap gap-3 mt-2 text-xs text-gray-500">
                          <span className="flex items-center gap-1">
                            <FaUser className="text-pink-500" />
                            {purchase.user_id?.user_name || "کاربر ناشناس"}
                          </span>
                          <span className="flex items-center gap-1">
                            <FaCalendar className="text-pink-500" />
                            {new Date(purchase.createdAt).toLocaleDateString("fa-IR")}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-2">
                    <div className="text-lg font-bold text-pink-500">
                      {parseInt(purchase.course_id?.price || 0).toLocaleString()} تومان
                    </div>
                    <button
                      onClick={() => {
                        setSelectedPurchase(purchase);
                        setShowModal(true);
                      }}
                      className="flex items-center gap-1 text-sm text-blue-500 hover:text-blue-600 transition"
                    >
                      <FaEye /> جزئیات بیشتر
                    </button>
                  </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 && selectedPurchase && (
          <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-[90vh] 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-between items-center">
                  <span className="text-gray-500">کاربر:</span>
                  <span className="font-medium">{selectedPurchase.user_id?.user_name || "-"}</span>
                </div>
                {/* <div className="flex justify-between items-center">
                  <span className="text-gray-500">ایمیل:</span>
                  <span className="text-sm">{selectedPurchase.user_id?.email || "-"}</span>
                </div> */}
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">دوره:</span>
                  <span>{selectedPurchase.course_id?.cuorse_name || "-"}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">مدرس:</span>
                  <span>{selectedPurchase.course_id?.teacher_name || "-"}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-500">تاریخ خرید:</span>
                  <span>{new Date(selectedPurchase.createdAt).toLocaleDateString("fa-IR")}</span>
                </div>
                {selectedPurchase.payment_ref_id && (
                  <div className="flex justify-between items-center">
                    <span className="text-gray-500">کد پیگیری:</span>
                    <span className="font-mono text-sm">{selectedPurchase.payment_ref_id}</span>
                  </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 Purchased;