import { FC, useState } from "react";
import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { toast } from "../../../components/Toast";
import DeleteNameConfirmModal from "../../../components/DeleteNameConfirmModal";
import PageLoading from "../../../components/PageLoading";
import { ErrorType } from "../../../helpers/types";
import { useGetWorkspaceDetail } from "../workspace/hooks/useWorkspaceData";
import { WorkspaceDetailType } from "../workspace/types/WorkspaceTypes";
import ProjectGrid from "./components/ProjectGrid";
import ProjectListHeader from "./components/ProjectListHeader";
import WorkspaceInfoBanner from "./components/WorkspaceInfoBanner";
import { useDeleteProject, useGetProjectsByWorkspace } from "./hooks/useProjectData";
import type { ProjectItem } from "./types/ProjectTypes";

const List: FC = () => {
  const { t } = useTranslation("global");
  const { workspaceId = "" } = useParams();
  const getProjects = useGetProjectsByWorkspace(workspaceId);
  const getWorkspaceDetail = useGetWorkspaceDetail(workspaceId);
  const deleteProject = useDeleteProject();

  const workspace: WorkspaceDetailType | undefined =
    getWorkspaceDetail.data?.data?.workspace ?? getWorkspaceDetail.data?.data;

  const projects: ProjectItem[] =
    getProjects.data?.data?.projects ?? getProjects.data?.data ?? [];

  const [deleteTarget, setDeleteTarget] = useState<ProjectItem | null>(null);

  const handleConfirmDelete = () => {
    if (!deleteTarget) return;

    deleteProject.mutate(
      { id: deleteTarget.id, workspaceId },
      {
        onSuccess: () => {
          toast(t("taskmanager.project_deleted"), "success");
          setDeleteTarget(null);
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], "error");
        },
      },
    );
  };

  const isLoading = getProjects.isPending || getWorkspaceDetail.isPending;

  return (
    <div className="w-full mt-4">
      <ProjectListHeader title={workspace?.name ?? ""} workspaceId={workspaceId} />

      {workspace?.description ? (
        <WorkspaceInfoBanner description={workspace.description} />
      ) : null}

      {isLoading ? (
        <PageLoading />
      ) : (
        <ProjectGrid projects={projects} onDelete={setDeleteTarget} />
      )}

      <DeleteNameConfirmModal
        isOpen={!!deleteTarget}
        close={() => setDeleteTarget(null)}
        onConfirm={handleConfirmDelete}
        isLoading={deleteProject.isPending}
        itemName={deleteTarget?.name ?? ""}
      />
    </div>
  );
};

export default List;
