"use client";

import { 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 { useUser } from "@/hooks/useUser";
import { Project } from "@/types/types";
import { statusMap } from "@/constants";

const Workroom = () => {
  const router = useRouter();
  const user = useUser();
  const [statusFilter, setStatusFilter] = useState("");

  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 = [
    { label: "دریافتی", value: "دریافتی", color: "#B89FFF" },
    { label: "پرداخت نشده", value: "پرداخت نشده", color: "#ddd" },
    { label: "در دست بررسی", value: "در دست بررسی", color: "#E0D891" },
    { label: "ارسال شده", value: "ارسال شده", color: "#ADF5FF" },
    { label: "منتشر شده", value: "منتشر شده", color: "#ADF5FF" },
    { label: "در دست اقدام", value: "در دست اقدام", color: "#E0D891" },
    { label: "اتمام پروژه", value: "اتمام پروژه", color: "#B7FFB6" },
    { label: "کنسل شده", value: "کنسل شده", color: "#FFC5C5" },
  ];

  const openProject = (item: Project) => {
    const creatorId =
      typeof item.creator_id === "string"
        ? item.creator_id
        : item.creator?._id;
    const isCreator =
      user?._id && creatorId && String(user._id) === String(creatorId);

    router.push(
      isCreator
        ? `/settings/workroom/${item._id}`
        : `/settings/workroom/user/${item._id}`
    );
  };

  return (
    <Container>
      <PageTitle>پروژه‌های من</PageTitle>
      <div className="px-4 text-xs md:text-sm">
        <div className="grid grid-cols-3 gap-2 px-4 text-sm">
          {statusOptions.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="mt-10 w-full">
          {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={() => openProject(item)}
                    >
                      <MainProjectCard
                        statusType={label}
                        color="#fff"
                        borderColor="#ccc"
                        textColor="#111"
                        project={item}
                      />
                    </div>
                  );
                })}
              </div>
            ))
          )}
        </div>
      </div>
    </Container>
  );
};

export default Workroom;
