"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import MainProjectCard from "@/components/projects/MainProjectCard";
import PageTitle from "@/components/settings/PageTitle";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { Project } from "@/types/types";
import { statusMap } from "@/constants";

const Workroom = () => {
  const router = useRouter();
  const [statusFilter, setStatusFilter] = useState("");
  const [userType, setUserType] = useState<string | null>("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      setUserType(localStorage.getItem("usertype"));
    }
  }, []);

  const { data, isFetchingNextPage } = useInfiniteScroll({
    endpoint: "/workroom",
    queryKey: ["workroom", statusFilter],
    params: { status_filter: statusFilter },
  });

  const getAdStatusAndColor = (statusType: string) =>
    statusMap[statusType as keyof typeof statusMap] ?? {
      label: "نامشخص",
      color: "#000",
    };

  const statusOptions = [
    { type: "user", label: "دریافتی", value: "دریافتی", color: "#B89FFF" },
    {
      type: "employer",
      label: "پرداخت نشده",
      value: "پرداخت نشده",
      color: "#ddd",
    },
    {
      type: "employer",
      label: "در دست بررسی",
      value: "در دست بررسی",
      color: "#E0D891",
    },
    { type: "user", label: "ارسال شده", value: "ارسال شده", color: "#ADF5FF" },
    {
      type: "employer",
      label: "منتشر شده",
      value: "منتشر شده",
      color: "#ADF5FF",
    },
    {
      type: "both",
      label: "در دست اقدام",
      value: "در دست اقدام",
      color: "#E0D891",
    },
    {
      type: "both",
      label: "اتمام پروژه",
      value: "اتمام پروژه",
      color: "#B7FFB6",
    },
    { type: "both", label: "کنسل شده", value: "کنسل شده", color: "#FFC5C5" },
  ];

  return (
    <Container>
      <PageTitle>اتاق کار</PageTitle>
      <div className="px-4 text-xs md:text-sm">
        <div className="px-4 text-sm grid grid-cols-3 gap-2">
          {statusOptions
            .filter(({ type }) => type === "both" || type === userType)
            .map(({ label, value, color }) => (
              <RoundedButton
                key={value}
                onClick={() => setStatusFilter(value)}
                className={`p-1 text-xs sm:p-2 md:text-sm ${
                  statusFilter === value ? ` text-primary-dark` : ""
                }`}
                style={{
                  backgroundColor: statusFilter === value ? color : "",
                  borderColor: statusFilter === value ? color : "",
                }}
              >
                {label}
              </RoundedButton>
            ))}
        </div>
        <div className="w-full mt-10">
          {data?.pages.length === 0 ||
          (data?.pages[0]?.projects?.length === 0 && !isFetchingNextPage) ? (
            <p className="text-center text-gray-500">پروژه ای ثبت نشده است.</p>
          ) : (
            data?.pages?.map((page, pageIndex) => (
              <div key={pageIndex}>
                {page?.projects?.map((item: Project) => {
                  const { label } = getAdStatusAndColor(item?.status);
                  return (
                    <div
                      key={item?._id}
                      className="cursor-pointer"
                      onClick={() => {
                        if (userType == "user") {
                          router.push(`/settings/workroom/user/${item?._id}`);
                        } else {
                          router.push(`/settings/workroom/${item?._id}`);
                        }
                      }}
                    >
                      <MainProjectCard
                        statusType={label}
                        color="#fff"
                        borderColor="#ccc"
                        textColor="#111"
                        project={item}
                      />
                    </div>
                  );
                })}
              </div>
            ))
          )}
        </div>
      </div>
    </Container>
  );
};

export default Workroom;
