// src/pages/Payments.js
import React, { useState, useEffect } from "react";
import toast from "react-hot-toast";
import {
  getPayments,
  updatePaymentStatus,
  getPaymentStats
} from "../../components/adminApi"; // اصلاح مسیر
import Layout from "../../components/academy/Layout";
import { FaFilter, FaTimes, FaFileExport, FaEye } from "react-icons/fa";
import { ImageBaseUrl } from "../../components/BaseUrl";

const Payments = () => {
  const [payments, setPayments] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedPayment, setSelectedPayment] = useState(null);
  const [showModal, setShowModal] = useState(false);
  const [filters, setFilters] = useState({
    status: "",
    startDate: "",
    endDate: "",
    search: ""
  });
  const [showFilters, setShowFilters] = useState(false);

  const fetchPayments = async () => {
    setLoading(true);
    try {
      const response = await getPayments({ page, limit: 15, ...filters });
      console.log("Payments response:", response.data);
      
      if (response.data.success) {
        // بررسی ساختار داده - طبق بک‌اند، data داخل response.data.data هست
        const responseData = response.data.data;
        setPayments(responseData?.payments || []);
        setStats(responseData?.stats || null);
        setTotalPages(responseData?.pagination?.totalPages || 1);
      } else {
        toast.error(response.data.message || "خطا در دریافت پرداخت‌ها");
      }
    } catch (error) {
      console.error("Error fetching payments:", error);
      toast.error("خطا در دریافت پرداخت‌ها");
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    fetchPayments();
    fetchStats();
  }, [page, filters.status, filters.startDate, filters.endDate, filters.search]);

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

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

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

  const exportToCSV = () => {
    const headers = ["کاربر", "دوره", "آکادمی", "مبلغ", "تاریخ", "وضعیت"];
    const rows = payments.map(p => [
      p.user_id?.user_name || "-",
      p.course_id?.cuorse_name || "-",
      p.academy_id?.academy_name || "-",
      p.price?.toLocaleString(),
      new Date(p.createdAt).toLocaleDateString("fa-IR"),
      p.status === "pending" ? "در انتظار" : p.status === "success" ? "موفق" : "تسویه شده"
    ]);

    const csvContent = [headers, ...rows].map(row => row.join(",")).join("\n");
    const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" }); // اضافه کردن BOM برای پشتیبانی از فارسی
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.setAttribute("download", `payments_${new Date().toISOString().slice(0, 19)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    toast.success("خروجی با موفقیت گرفته شد");
  };

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

  console.log(payments);
  

  return (
    <Layout>
      <div className="p-6">
        <div className="flex justify-between items-center mb-6 flex-wrap gap-4">
          <h1 className="text-2xl font-bold">مدیریت پرداخت‌ها</h1>
          <div className="flex gap-2">
            <button
              onClick={exportToCSV}
              disabled={payments.length === 0}
              className="flex items-center gap-2 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <FaFileExport />
              خروجی Excel
            </button>
            <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>
        </div>

        {/* Stats Cards */}
        {stats && (
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
            {/* <div className="bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg p-4 text-white">
              <p className="text-sm opacity-90">کل مبلغ</p>
              <p className="text-2xl font-bold">{stats.totalAmount?.toLocaleString() || 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.totalCount || 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-blue-600">{stats.successCount || 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.settledCount || 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="success">موفق</option>
                <option value="settled">تسویه شده</option>
              </select>
              <input
                type="date"
                name="startDate"
                placeholder="از تاریخ"
                value={filters.startDate}
                onChange={handleFilterChange}
                className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
              />
              <input
                type="date"
                name="endDate"
                placeholder="تا تاریخ"
                value={filters.endDate}
                onChange={handleFilterChange}
                className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
              />
            </div>
          </div>
        )}

        {/* Payments Table */}
        <div className="bg-white rounded-lg shadow overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[1000px]">
              <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>
                {payments.length === 0 ? (
                  <tr>
                    <td colSpan={8} className="text-center py-8 text-gray-500">
                      هیچ پرداختی یافت نشد
                    </td>
                  </tr>
                ) : (
                  payments.map((payment) => (
                    <tr key={payment._id} className="border-t hover:bg-gray-50">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">
                            {payment.user_id?.profile_image ? (
                              <img src={ImageBaseUrl + payment.user_id.profile_image} alt="" className="w-full h-full object-cover" />
                            ) : (
                              <span className="text-xs">👤</span>
                            )}
                          </div>
                          <div>
                            <p className="font-medium">{payment.user_id?.user_name || "-"}</p>
                            <p className="text-xs text-gray-500">{payment.user_id?.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <p className="font-medium">{payment.course_id?.cuorse_name || "-"}</p>
                        <p className="text-xs text-gray-500">مدرس: {payment.course_id?.teacher_name || "-"}</p>
                      </td>
                      <td className="px-4 py-3">{payment.academy_id?.academy_name || "-"}</td>
                      <td className="px-4 py-3 font-bold">{payment.taxAmount?.toLocaleString()} تومان</td>
                      <td className="px-4 py-3 text-xs font-mono">{payment.payment_ref_id?.slice(-8) || "-"}</td>
                      <td className="px-4 py-3">{new Date(payment.createdAt).toLocaleDateString("fa-IR")}</td>
                      <td className="px-4 py-3">{getStatusBadge(payment.status)}</td>
                      <td className="px-4 py-3">
                        <div className="flex gap-2 flex-wrap">
                          <button
                            onClick={() => {
                              setSelectedPayment(payment);
                              setShowModal(true);
                            }}
                            className="p-1 text-blue-500 hover:text-blue-700"
                            title="جزئیات"
                          >
                            <FaEye />
                          </button>
                          {payment.status === "success" && (
                            <button
                              onClick={() => handleStatusChange(payment._id, "settled")}
                              className="px-2 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600"
                            >
                              تسویه
                            </button>
                          )}
                          {payment.status === "pending" && (
                            <button
                              onClick={() => handleStatusChange(payment._id, "success")}
                              className="px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600"
                            >
                              تأیید
                            </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"
            >
              قبلی
            </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"
            >
              بعدی
            </button>
          </div>
        )}

        {/* Modal for Payment Details */}
        {showModal && selectedPayment && (
          <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">
                  <FaTimes />
                </button>
              </div>
              <div className="p-4 space-y-3">
                <div className="flex justify-between">
                  <span className="text-gray-500">کاربر:</span>
                  <span className="font-medium">{selectedPayment.user_id?.user_name}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">دوره:</span>
                  <span>{selectedPayment.course_id?.cuorse_name}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">آکادمی:</span>
                  <span>{selectedPayment.academy_id?.academy_name}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">شبا اکادمی:</span>
                  <span>{selectedPayment.academy_id?.sheba}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">مبلغ:</span>
                  <span className="font-bold text-pink-500">{selectedPayment.price?.toLocaleString()} تومان</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">تخفیف:</span>
                  <span>{selectedPayment.discountAmount || 0} تومان</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">مبلغ با مالیات:</span>
                  <span>{selectedPayment.taxAmount || 0} تومان</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">کد پیگیری:</span>
                  <span className="font-mono text-sm">{selectedPayment.payment_ref_id}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">تاریخ:</span>
                  <span>{new Date(selectedPayment.createdAt).toLocaleDateString("fa-IR")}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">وضعیت:</span>
                  <span>{getStatusBadge(selectedPayment.status)}</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"
                >
                  بستن
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </Layout>
  );
};

export default Payments;