// src/pages/Courses.js
import React, { useState, useEffect } from "react";
import toast from "react-hot-toast";
import {
  getCourses,
  updateCourseStatus,
  deleteCourse,
  getCourseStats,
} from "../../components/adminApi";
import Layout from "../../components/academy/Layout";
import {
  FaTrash,
  FaFilter,
} from "react-icons/fa";

const Courses = () => {
  const [courses, setCourses] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [filters, setFilters] = useState({
    status: "",
    type: "",
    category: "",
    search: "",
  });
  const [showFilters, setShowFilters] = useState(false);

  const fetchCourses = async () => {
    setLoading(true);
    try {
      const response = await getCourses({ page, limit: 10, ...filters });
      console.log("Courses response:", response.data);

      if (response.data.success) {
        const responseData = response.data.data;
        setCourses(responseData?.courses || []);
        setStats(responseData?.stats || null);
        setTotalPages(responseData?.pagination?.totalPages || 1);
      } else {
        toast.error(response.data.message || "خطا در دریافت دوره‌ها");
      }
    } catch (error) {
      console.error("Error fetching courses:", error);
      toast.error("خطا در دریافت دوره‌ها");
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      const response = await getCourseStats();
      console.log("Stats response:", response.data);

      if (response.data.success) {
        setStats(response.data.data);
      }
    } catch (error) {
      console.error("Error fetching stats:", error);
    }
  };

  useEffect(() => {
    fetchCourses();
    fetchStats();
  }, [page, filters.status, filters.type, filters.category, filters.search]);

// تغییر وضعیت (status)
const handleStatusChange = async (courseId, newStatus) => {
  console.log("Changing status:", { courseId, newStatus });
  try {
    const response = await updateCourseStatus({ courseId, status: newStatus });
    console.log("Response:", response.data);

    if (response.data.success) {
      toast.success("وضعیت دوره تغییر کرد");
      
      // ✅ آپدیت مستقیم state بدون نیاز به fetch جدید
      setCourses(prevCourses => 
        prevCourses.map(course => 
          course._id === courseId 
            ? { ...course, status: newStatus }
            : course
        )
      );
      
      // آپدیت stats
      if (stats) {
        // کاهش/افزایش آمار
        const oldStatus = courses.find(c => c._id === courseId)?.status;
        if (oldStatus === "pending" && newStatus === "accept") {
          setStats(prev => ({
            ...prev,
            pendingCount: (prev.pendingCount || 0) - 1,
            acceptCount: (prev.acceptCount || 0) + 1
          }));
        } else if (oldStatus === "pending" && newStatus === "reject") {
          setStats(prev => ({
            ...prev,
            pendingCount: (prev.pendingCount || 0) - 1,
            rejectCount: (prev.rejectCount || 0) + 1
          }));
        }
      }
      
      // فقط stats رو رفرش کن
      fetchStats();
    } else {
      toast.error(response.data.message || "خطا در تغییر وضعیت");
    }
  } catch (error) {
    console.error("Error updating status:", error);
    toast.error("خطا در تغییر وضعیت");
  }
};

// تغییر نوع (type)
const handleTypeChange = async (courseId, newType) => {
  console.log("Changing type:", { courseId, newType });
  try {
    const response = await updateCourseStatus({ courseId, type: newType });
    console.log("Response:", response.data);

    if (response.data.success) {
      toast.success("نوع دوره تغییر کرد");
      
      // ✅ آپدیت مستقیم state
      setCourses(prevCourses => 
        prevCourses.map(course => 
          course._id === courseId 
            ? { ...course, type: newType }
            : course
        )
      );
    } else {
      toast.error(response.data.message || "خطا در تغییر نوع");
    }
  } catch (error) {
    console.error("Error updating type:", error);
    toast.error("خطا در تغییر نوع");
  }
};
  const handleDelete = async (courseId) => {
    if (window.confirm("آیا از حذف این دوره مطمئن هستید؟")) {
      try {
        const response = await deleteCourse(courseId);
        if (response.data.success) {
          toast.success("دوره حذف شد");
          fetchCourses();
          fetchStats();
        } else {
          toast.error(response.data.message || "خطا در حذف دوره");
        }
      } catch (error) {
        console.error("Error deleting course:", error);
        toast.error("خطا در حذف دوره");
      }
    }
  };

  const handleFilterChange = (e) => {
    setFilters({
      ...filters,
      [e.target.name]: e.target.value,
    });
    setPage(1);
  };

  const clearFilters = () => {
    setFilters({
      status: "",
      type: "",
      category: "",
      search: "",
    });
    setPage(1);
  };

  const getStatusBadge = (status) => {
    const badges = {
      pending: "bg-yellow-500",
      accept: "bg-green-500",
      reject: "bg-red-500",
    };
    const texts = {
      pending: "در انتظار",
      accept: "تایید شده",
      reject: "رد شده",
    };
    return (
      <span
        className={`px-2 py-1 rounded text-xs text-white ${
          badges[status] || "bg-gray-500"
        }`}
      >
        {texts[status] || status}
      </span>
    );
  };

  const getTypeBadge = (type) => {
    const badges = {
      normal: "bg-blue-500",
      pro: "bg-purple-500",
      legend: "bg-pink-500",
    };
    const texts = {
      normal: "معمولی",
      pro: "پرو",
      legend: "لجند",
    };
    return (
      <span
        className={`px-2 py-1 rounded text-xs text-white ${
          badges[type] || "bg-gray-500"
        }`}
      >
        {texts[type] || type}
      </span>
    );
  };

  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="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">مدیریت دوره‌ها</h1>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className="flex items-center gap-2 px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
          >
            <FaFilter />
            فیلترها
            {Object.values(filters).some((v) => v) && (
              <span className="w-2 h-2 bg-pink-500 rounded-full"></span>
            )}
          </button>
        </div>

        {/* Stats */}
        {stats && (
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
            <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.totalCourses || 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 text-green-600">
                {stats.acceptCount || 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 text-yellow-600">
                {stats.pendingCount || 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 text-purple-600">
                {stats.proCount || 0}
              </p>
            </div>
          </div>
        )}

        {/* Filters Panel */}
        {showFilters && (
          <div className="bg-white rounded-lg p-4 shadow-sm mb-6 border">
            <div className="flex justify-between items-center mb-4">
              <h3 className="font-semibold">فیلترها</h3>
              <button
                onClick={clearFilters}
                className="text-sm text-pink-500 hover:text-pink-600"
              >
                پاک کردن همه
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <input
                type="text"
                name="search"
                placeholder="جستجو..."
                value={filters.search}
                onChange={handleFilterChange}
                className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
              />
              <select
                name="status"
                value={filters.status}
                onChange={handleFilterChange}
                className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
              >
                <option value="">همه وضعیت‌ها</option>
                <option value="pending">در انتظار</option>
                <option value="accept">تایید شده</option>
                <option value="reject">رد شده</option>
              </select>
              <select
                name="type"
                value={filters.type}
                onChange={handleFilterChange}
                className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
              >
                <option value="">همه نوع‌ها</option>
                <option value="normal">معمولی</option>
                <option value="pro">پرو</option>
                <option value="legend">لجند</option>
              </select>
              <input
                type="text"
                name="category"
                placeholder="دسته بندی"
                value={filters.category}
                onChange={handleFilterChange}
                className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
              />
            </div>
          </div>
        )}

        {/* Courses Table */}
        <div className="bg-white rounded-lg shadow overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[900px]">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-right">نام دوره</th>
                  <th className="px-4 py-3 text-right">مدرس</th>
                  <th className="px-4 py-3 text-right">دسته بندی</th>
                  <th className="px-4 py-3 text-right">قیمت</th>
                  <th className="px-4 py-3 text-right">تخفیف</th>
                  <th className="px-4 py-3 text-right">نوع</th>
                  <th className="px-4 py-3 text-right">وضعیت</th>
                  <th className="px-4 py-3 text-right">عملیات</th>
                </tr>
              </thead>
              <tbody>
                {courses.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="text-center py-8 text-gray-500">
                      هیچ دوره‌ای یافت نشد
                    </td>
                  </tr>
                ) : (
                  courses.map((course) => (
                    <tr key={course._id} className="border-t hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <div>
                          <p className="font-medium">{course.cuorse_name}</p>
                          <p className="text-xs text-gray-500 line-clamp-1">
                            {course.caption?.substring(0, 50)}
                          </p>
                        </div>
                      </td>
                      <td className="px-4 py-3">{course.teacher_name}</td>
                      <td className="px-4 py-3">{course.category}</td>
                      <td className="px-4 py-3">
                        {parseInt(course.price).toLocaleString()} تومان
                      </td>
                      <td className="px-4 py-3">
                        {course.offer ? `${course.offer}%` : "-"}
                      </td>
                      <td className="px-4 py-3">{getTypeBadge(course.type)}</td>
                      <td className="px-4 py-3">
                        {getStatusBadge(course.status)}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex gap-2 flex-wrap">
                          <select
                            onChange={(e) => handleStatusChange(course._id, e.target.value)}
                            value={course.status}
                            className="text-xs px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-pink-500"
                          >
                            <option value="pending">در انتظار</option>
                            <option value="accept">تایید</option>
                            <option value="reject">رد</option>
                          </select>

                          <select
                            onChange={(e) => handleTypeChange(course._id, e.target.value)}
                            value={course.type}
                            className="text-xs px-2 py-1 border rounded focus:outline-none focus:ring-1 focus:ring-pink-500"
                          >
                            <option value="normal">معمولی</option>
                            <option value="pro">پرو</option>
                            <option value="legend">لجند</option>
                          </select>
                          
                          <button
                            onClick={() => handleDelete(course._id)}
                            className="p-1 text-red-500 hover:text-red-700 transition"
                            title="حذف دوره"
                          >
                            <FaTrash />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </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>
        )}
      </div>
    </Layout>
  );
};

export default Courses;