import React, { useEffect, useState, useMemo } from "react";
import AdminHeader from "../../components/admin-header";
import Sidebar from "../../components/sidebar";
import { useNavigate } from "react-router-dom";
import { BaseUrl } from "../../components/BaseUrl";
import axios from "axios";
import Loading from "../../components/elements/loading";
import toast from "react-hot-toast";
import Pagination from "../../components/Pagination";
import Filters from "../../components/Filters";

const statusMap = {
  all: { label: "همه", class: "text-yellow-300" },
  pre_payment: { label: "پرداخت نشده", class: "text-yellow-300" },
  paid: { label: "در دست بررسی", class: "text-yellow-300" },
  accepted: { label: "منتشر شده", class: "text-green-300" },
  ongoing: { label: "در دست اقدام", class: "text-green-300" },
  done: { label: "انجام شده", class: "text-green-300" },
  rejected: { label: "رد شده", class: "text-red-300" },
  cancled: { label: "کنسل شده", class: "text-red-300" },
};

const Projects = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [projectsList, setProjectsList] = useState([]);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [filters, setFilters] = useState({ startDate: "", endDate: "", status: "" });

  const getProjectList = async (page = 1) => {
    try {
      setLoading(true);
      const { startDate, endDate, status } = filters;
      const res = await axios.get(
        `${BaseUrl}/projects?limit=20&page=${page}${startDate ? "&startDate=" + startDate : ""
        }${endDate ? "&endDate=" + endDate : ""}${status ? "&status=" + status : ""}`
      );
      setProjectsList(res?.data?.projects || []);
      setTotalPages(res?.data?.totalPages || 0);
    } catch (err) {
      toast.error("خطا در دریافت لیست پروژه‌ها");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getProjectList(currentPage);
  }, [currentPage, filters]);

  const toggleProjectStatus = async (project) => {
    try {
      const newStatus = project.status === "accepted" ? "rejected" : "accepted";
      await axios.post(`${BaseUrl}/projects/accept`, {
        id: project._id,
        user_id: project?.selected_user?._id,
        status: newStatus,
      });
      toast.success(`پروژه ${newStatus === "accepted" ? "تأیید" : "رد"} شد`);
      getProjectList(currentPage);
    } catch (error) {
      toast.error(error?.response?.data?.message || "خطا در تغییر وضعیت");
    }
  };

  return (
    <>
     
      <div className="min-h-screen mx-auto flex bg-gray-900">
      <div className="  w-64"><Sidebar /></div>
        <div className="w-full h-full p-14 mb-11 mx-auto text-white">
          {/* فیلترها */}
          <Filters
            statusOptions={Object.entries(statusMap).map(([key, val]) => ({
              key,
              label: val.label,
            }))}
            provinceOptions={[{ value: "", label: "همه استان‌ها" }]}
            cityOptions={[{ value: "", label: "همه شهرها" }]}
            photographyModelOptions={[{ value: "", label: "همه مدل‌ها" }]}
            blockStatusOptions={[{ value: "", label: "همه کاربران" }]}
            onFilterChange={setFilters}
          />

          {/* هدر جدول */}
          <div className="w-full mt-4 flex items-center border-b pb-2 text-sm font-KalamehMed">
            {[
              "عنوان پروژه",
              "کارفرما",
              "کاربر",
              "تخصص",
              "زمان پیشنهادی",
              "زمان نهایی",
              "قیمت پیشنهادی",
              "قیمت نهایی",
              "تاریخ ثبت",
              "وضعیت",
              "عملیات",
            ].map((title, idx) => (
              <div key={idx} className="w-[10%]">{title}</div>
            ))}
          </div>

          {/* لیست پروژه‌ها */}
          {loading ? (
            <div className="flex justify-center mt-5">
              <Loading className="w-14 h-14 text-blacklead animate-pulse" />
            </div>
          ) : (
            <div className="overflow-y-scroll hide-scrollbar w-full max-h-[70vh] mt-2">
              {projectsList.map((project, index) => {
                const statusInfo = statusMap[project?.status] || { label: "-", class: "text-gray-300" };
                return (
                  <div
                    key={project._id}
                    className={`flex items-center px-4 py-3 rounded-md mb-2 ${index % 2 === 0 ? "bg-[#2e2e2e]" : "bg-[#3a3a3a]"}`}
                  >
                    <div className="w-[10%]">{project?.title}</div>
                    <div className="w-[10%]">{project?.creator?.first_name} {project?.creator?.last_name}</div>
                    <div className="w-[10%]">{project?.selected_user?.first_name} {project?.selected_user?.last_name}</div>
                    <div className="w-[10%]">{project?.expertise}</div>
                    <div className="w-[10%]">{project?.offer_time}</div>
                    <div className="w-[10%]">{project?.final_time}</div>
                    <div className="w-[10%]">{Number(project?.offer_price).toLocaleString()}</div>
                    <div className="w-[10%]">{Number(project?.final_price).toLocaleString()}</div>
                    <div className="w-[10%]">{new Date(project?.createdAt).toLocaleDateString("fa-IR")}</div>
                    <div className={`w-[10%] ${statusInfo.class}`}>{statusInfo.label}</div>
                    <div className="w-[10%] flex gap-2">
                      <button
                        onClick={() => navigate(`${project?._id}`)}
                        className="bg-blue-600 hover:bg-blue-700 px-3 py-1 rounded"
                      >
                        جزئیات
                      </button>
                      <button
                        onClick={() => toggleProjectStatus(project)}
                        className="bg-green-600 hover:bg-green-700 px-3 py-1 rounded"
                      >
                        {project.status === "accepted" ? "رد" : "تأیید"}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* صفحه‌بندی */}
          <Pagination
            totalPages={totalPages}
            currentPage={currentPage}
            onPageChange={(page) => setCurrentPage(page)}
          />
        </div>
      </div>
    </>
  );
};

export default Projects;
