"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 LocalePageShell from "@/components/i18n/LocalePageShell";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { useUser } from "@/hooks/useUser";
import { Project } from "@/types/types";
import { useTranslation } from "react-i18next";
import { statusMap } from "@/constants";
import {
  listProjectDrafts,
  ProjectDraft,
  removeProjectDraft,
} from "@/lib/projectDrafts";

const STATUS_OPTIONS = [
  { key: "received", value: "دریافتی", color: "#B89FFF" },
  { key: "unpaid", value: "پرداخت نشده", color: "#ddd" },
  { key: "reviewing", value: "در دست بررسی", color: "#E0D891" },
  { key: "sent", value: "ارسال شده", color: "#ADF5FF" },
  { key: "published", value: "منتشر شده", color: "#ADF5FF" },
  { key: "inProgress", value: "در دست اقدام", color: "#E0D891" },
  { key: "completed", value: "اتمام پروژه", color: "#B7FFB6" },
  { key: "cancelled", value: "کنسل شده", color: "#FFC5C5" },
] as const;

const Workroom = () => {
  const { t } = useTranslation("common");
  const router = useRouter();
  const user = useUser();
  const [statusFilter, setStatusFilter] = useState("");
  const [showDrafts, setShowDrafts] = useState(false);
  const [drafts, setDrafts] = useState<ProjectDraft[]>([]);

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

  useEffect(() => {
    if (showDrafts) setDrafts(listProjectDrafts());
  }, [showDrafts]);

  const getStatusLabel = (statusType?: string) => {
    if (!statusType) return t("settings.unknown");
    const entry = statusMap[statusType as keyof typeof statusMap];
    if (entry?.labelKey) return t(entry.labelKey);
    return t("settings.unknown");
  };

  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 (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.nav.workroom")}</PageTitle>
        <div className="px-4 text-xs md:text-sm">
          <div className="grid grid-cols-3 gap-2 px-4 text-sm">
            <RoundedButton
              onClick={() => {
                setShowDrafts(true);
                setStatusFilter("");
              }}
              className={`p-1 text-xs sm:p-2 md:text-sm ${
                showDrafts ? "text-primary-dark" : ""
              }`}
              style={{
                backgroundColor: showDrafts ? "#FFD6E7" : "",
                borderColor: showDrafts ? "#FFD6E7" : "",
              }}
            >
              {t("settings.workroom.drafts")}
            </RoundedButton>
            {STATUS_OPTIONS.map(({ key, value, color }) => (
              <RoundedButton
                key={value}
                onClick={() => {
                  setShowDrafts(false);
                  setStatusFilter(value);
                }}
                className={`p-1 text-xs sm:p-2 md:text-sm ${
                  !showDrafts && statusFilter === value
                    ? " text-primary-dark"
                    : ""
                }`}
                style={{
                  backgroundColor:
                    !showDrafts && statusFilter === value ? color : "",
                  borderColor:
                    !showDrafts && statusFilter === value ? color : "",
                }}
              >
                {t(`settings.workroom.statuses.${key}`)}
              </RoundedButton>
            ))}
          </div>
          <div className="mt-10 w-full">
            {showDrafts ? (
              drafts.length === 0 ? (
                <p className="text-center text-gray-500">
                  {t("settings.workroom.draftsEmpty")}
                </p>
              ) : (
                <div className="flex flex-col gap-3">
                  {drafts.map((draft) => (
                    <div
                      key={draft.id}
                      className="rounded-3xl border border-border-secondary-light p-4 dark:border-border-secondary-dark"
                    >
                      <button
                        type="button"
                        className="w-full text-right"
                        onClick={() =>
                          router.push(`/new-project?draft=${draft.id}`)
                        }
                      >
                        <p className="font-semibold text-text-blue-light dark:text-text-blue-dark">
                          {draft.title}
                        </p>
                        <p className="mt-1 text-xs text-neutral-500">
                          {t("settings.workroom.draftStep", {
                            step: draft.step,
                          })}
                          {" · "}
                          {new Date(draft.updatedAt).toLocaleDateString("fa-IR")}
                        </p>
                      </button>
                      <div className="mt-3 flex gap-2">
                        <RoundedButton
                          type="button"
                          variant="primary"
                          className="h-8 flex-1 text-xs"
                          onClick={() =>
                            router.push(`/new-project?draft=${draft.id}`)
                          }
                        >
                          {t("settings.workroom.continueDraft")}
                        </RoundedButton>
                        <RoundedButton
                          type="button"
                          className="h-8 flex-1 text-xs"
                          onClick={() => {
                            removeProjectDraft(draft.id);
                            setDrafts(listProjectDrafts());
                          }}
                        >
                          {t("settings.workroom.deleteDraft")}
                        </RoundedButton>
                      </div>
                    </div>
                  ))}
                </div>
              )
            ) : data?.pages.length === 0 ||
              (data?.pages[0]?.projects?.length === 0 &&
                !isFetchingNextPage) ? (
              <p className="text-center text-gray-500">
                {t("settings.workroom.empty")}
              </p>
            ) : (
              data?.pages?.map((page, pageIndex) => (
                <div key={pageIndex}>
                  {page?.projects?.map((item: Project) => (
                    <div
                      key={item?._id}
                      className="cursor-pointer"
                      onClick={() => openProject(item)}
                    >
                      <MainProjectCard
                        statusType={getStatusLabel(item?.status)}
                        color="#fff"
                        borderColor="#ccc"
                        textColor="#111"
                        project={item}
                      />
                    </div>
                  ))}
                </div>
              ))
            )}
          </div>
        </div>
      </Container>
    </LocalePageShell>
  );
};

export default Workroom;
