// src/pages/Dashboard.js
import React, { useState, useEffect } from "react";
import Layout from "../../components/academy/Layout";
import {
  getPaymentStats,
  getCourseStats,
  getPurchasedStats,
  getAcademyStats,
  getPayments,    
  getCourses      
} from "../../components/adminApi";
import { Link } from "react-router-dom";
import { FaWallet, FaBook, FaShoppingCart, FaUniversity, FaStar } from "react-icons/fa";

const Dashboard = () => {
  const [stats, setStats] = useState({
    payments: { totalAmount: 0, totalCount: 0, pendingCount: 0, successCount: 0, settledCount: 0 },
    courses: { totalCourses: 0, acceptCount: 0, pendingCount: 0, normalCount: 0, proCount: 0, legendCount: 0 },
    purchased: { totalPurchases: 0, uniqueUsers: 0 },
    academies: { totalAcademies: 0, avgRate: 0 }
  });
  const [loading, setLoading] = useState(true);
  const [recentPayments, setRecentPayments] = useState([]);
  const [recentCourses, setRecentCourses] = useState([]);

  useEffect(() => {
    const fetchStats = async () => {
      setLoading(true);
      try {
        const [paymentsRes, coursesRes, purchasedRes, academiesRes] = await Promise.all([
          getPaymentStats(),
          getCourseStats(),
          getPurchasedStats(),
          getAcademyStats()
        ]);

        console.log("Payment Stats:", paymentsRes.data);
        console.log("Course Stats:", coursesRes.data);
        console.log("Purchased Stats:", purchasedRes.data);
        console.log("Academy Stats:", academiesRes.data);

        setStats({
          payments: paymentsRes.data?.data || {},
          courses: coursesRes.data?.data || {},
          purchased: purchasedRes.data?.data || {},
          academies: academiesRes.data?.data || {}
        });
      } catch (error) {
        console.error("Error fetching stats:", error);
      } finally {
        setLoading(false);
      }
    };

    const fetchRecentData = async () => {
      try {
        // دریافت 5 پرداخت آخر
        const paymentsRes = await getPayments({ page: 1, limit: 5 });
        if (paymentsRes.data?.success) {
          setRecentPayments(paymentsRes.data.data?.payments || []);
        }

        // دریافت 5 دوره آخر
        const coursesRes = await getCourses({ page: 1, limit: 5 });
        if (coursesRes.data?.success) {
          setRecentCourses(coursesRes.data.data?.courses || []);
        }
      } catch (error) {
        console.error("Error fetching recent data:", error);
      }
    };

    fetchStats();
    fetchRecentData();
  }, []);

  const statCards = [
    // {
    //   title: "مجموع فروش",
    //   value: stats.payments.totalAmount?.toLocaleString() || 0,
    //   unit: "تومان",
    //   icon: <FaWallet className="text-2xl" />,
    //   bgColor: "bg-blue-100",
    //   textColor: "text-blue-600",
    //   iconBg: "bg-blue-500"
    // },
    {
      title: "تعداد پرداخت‌ها",
      value: stats.payments.totalCount || 0,
      unit: "",
      icon: <FaWallet className="text-2xl" />,
      bgColor: "bg-green-100",
      textColor: "text-green-600",
      iconBg: "bg-green-500"
    },
    {
      title: "دوره‌های تایید شده",
      value: stats.courses.acceptCount || 0,
      unit: "",
      subValue: `در انتظار: ${stats.courses.pendingCount || 0}`,
      icon: <FaBook className="text-2xl" />,
      bgColor: "bg-purple-100",
      textColor: "text-purple-600",
      iconBg: "bg-purple-500"
    },
    {
      title: "کل دوره‌ها",
      value: stats.courses.totalCourses || 0,
      unit: "",
      icon: <FaBook className="text-2xl" />,
      bgColor: "bg-indigo-100",
      textColor: "text-indigo-600",
      iconBg: "bg-indigo-500"
    },
    {
      title: "خریدهای انجام شده",
      value: stats.purchased.totalPurchases || 0,
      unit: "",
      icon: <FaShoppingCart className="text-2xl" />,
      bgColor: "bg-orange-100",
      textColor: "text-orange-600",
      iconBg: "bg-orange-500"
    },
    {
      title: "کاربران خریدار",
      value: stats.purchased.uniqueUsers || 0,
      unit: "نفر",
      icon: <FaShoppingCart className="text-2xl" />,
      bgColor: "bg-rose-100",
      textColor: "text-rose-600",
      iconBg: "bg-rose-500"
    },
    {
      title: "آکادمی‌ها",
      value: stats.academies.totalAcademies || 0,
      unit: "",
      icon: <FaUniversity className="text-2xl" />,
      bgColor: "bg-teal-100",
      textColor: "text-teal-600",
      iconBg: "bg-teal-500"
    },
    // {
    //   title: "میانگین امتیاز",
    //   value: stats.academies.avgRate?.toFixed(1) || 0,
    //   unit: "از 5",
    //   icon: <FaStar className="text-2xl" />,
    //   bgColor: "bg-yellow-100",
    //   textColor: "text-yellow-600",
    //   iconBg: "bg-yellow-500"
    // }
  ];

  const getStatusBadge = (status) => {
    const badges = {
      pending: "bg-yellow-100 text-yellow-700",
      accept: "bg-green-100 text-green-700",
      success: "bg-blue-100 text-blue-700",
      settled: "bg-purple-100 text-purple-700",
    };
    const texts = {
      pending: "در انتظار",
      accept: "تایید شده",
      success: "موفق",
      settled: "تسویه شده",
    };
    return (
      <span className={`px-2 py-1 rounded text-xs ${badges[status] || "bg-gray-100 text-gray-700"}`}>
        {texts[status] || status}
      </span>
    );
  };

  console.log(stats);
  

  if (loading) {
    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 text-gray-800">داشبورد مدیریتی</h1>
          <p className="text-gray-500 mt-1">خلاصه وضعیت سیستم</p>
        </div>

        {/* Stat Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          {statCards.map((card, index) => (
            <div
              key={index}
              className="bg-white rounded-xl shadow-md p-6 hover:shadow-lg transition-all hover:-translate-y-1"
            >
              <div className="flex justify-between items-start">
                <div>
                  <p className="text-gray-500 text-sm">{card.title}</p>
                  <p className="text-2xl font-bold text-gray-800 mt-2">
                    {card.value}
                    {card.unit && <span className="text-sm mr-1 text-gray-500">{card.unit}</span>}
                  </p>
                  {card.subValue && (
                    <p className="text-xs text-gray-400 mt-1">{card.subValue}</p>
                  )}
                </div>
                <div className={`${card.bgColor} p-3 rounded-lg`}>
                  <div className={card.textColor}>{card.icon}</div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Recent Payments & Courses */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* آخرین پرداخت‌ها */}
          <div className="bg-white rounded-xl shadow-md overflow-hidden">
            <div className="px-6 py-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-semibold">آخرین پرداخت‌ها</h3>
              <Link to="/payments" className="text-sm text-pink-500 hover:text-pink-600">
                مشاهده همه
              </Link>
            </div>
            <div className="p-4">
              {recentPayments.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <FaWallet className="text-4xl mx-auto mb-2 text-gray-300" />
                  <span>هیچ پرداختی یافت نشد</span>
                </div>
              ) : (
                <div className="space-y-3">
                  {recentPayments.map((payment) => (
                    <div key={payment._id} className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-medium">{payment.course_id?.cuorse_name || "-"}</p>
                        <p className="text-xs text-gray-500">{payment.user_id?.user_name}</p>
                      </div>
                      <div className="text-right">
                        <p className="font-bold text-pink-600">{payment.price?.toLocaleString()} تومان</p>
                        {getStatusBadge(payment.status)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* آخرین دوره‌ها */}
          <div className="bg-white rounded-xl shadow-md overflow-hidden">
            <div className="px-6 py-4 border-b flex justify-between items-center">
              <h3 className="text-lg font-semibold">آخرین دوره‌ها</h3>
              <Link to="/courses" className="text-sm text-pink-500 hover:text-pink-600">
                مشاهده همه
              </Link>
            </div>
            <div className="p-4">
              {recentCourses.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <FaBook className="text-4xl mx-auto mb-2 text-gray-300" />
                  <span>هیچ دوره‌ای یافت نشد</span>
                </div>
              ) : (
                <div className="space-y-3">
                  {recentCourses.map((course) => (
                    <div key={course._id} className="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-medium">{course.cuorse_name}</p>
                        <p className="text-xs text-gray-500">{course.teacher_name}</p>
                      </div>
                      <div className="text-right">
                        <p className="font-bold text-pink-600">{parseInt(course.price).toLocaleString()} تومان</p>
                        {getStatusBadge(course.status)}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default Dashboard;