/* eslint-disable @typescript-eslint/no-explicit-any */
import { BASE_URL } from "@/components/main/BaseUrl";
import React from "react";
import { cookies } from "next/headers";
import { IProjectRequest, Project, SelectedUser } from "@/types/types";
import Container from "@/components/elements/Container";
import MainProjectCard from "@/components/projects/MainProjectCard";
import { statusMap } from "@/constants";
import ProjectWorkroomSelectedUser from "@/components/projects/Workroom/ProjectWorkroomSelectedUser";
import ProjectRequests from "@/components/projects/ProjectPage/ProjectRequests";

interface IProjectProps {
  params: Promise<{ id: string }>;
}

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

async function ProjectPage({ params }: IProjectProps) {
  const { id } = await params;
  const token = (await cookies()).get("token")?.value || "";

  try {
    const response = await fetch(`${BASE_URL}/workroom/get?projectId=${id}`, {
      cache: "no-store",
      headers: {
        Authorization: token ? `Bearer ${token}` : "",
      },
    });

    if (!response.ok) {
      throw new Error(`خطا در دریافت اطلاعات: ${response.status}`);
    }

    const data = await response.json();
    const project = data.project as Project;
    const projectRequests = data.projectRequests as IProjectRequest[];
    const { label } = getAdStatusAndColor(project?.status);
    let selectedUser;
    if (project?.selected_user) {
      selectedUser = project?.selected_user as SelectedUser;
    }
    console.log(data);

    return (
      <Container>
        <h1 className="font-bold text-xl text-center line-clamp-2 mb-5 mt-10">
          {project?.title}
        </h1>
        <div className="px-4">
          <MainProjectCard
            color="#fff"
            borderColor="#ccc"
            textColor="#111"
            statusType={label}
            project={project}
            full={true}
          />
          {/* {status == "ongoing" && selected_user && (
            <ProjectWorkroomRate
              projectId={id}
              selected_user={selected_user}
            />
          )} */}
          <>
            {project?.status == "done" && selectedUser && (
              <ProjectWorkroomSelectedUser selectedUser={selectedUser} />
            )}
            <p className="my-4 text-center font-semibold">
              کاربرانی که برای این پروژه درخواست ارسال کرده اند
            </p>
            <ProjectRequests projectRequests={projectRequests} />
          </>
        </div>
      </Container>
    );
  } catch (error: any) {
    return (
      <Container>
        <h1 className="text-red-500 text-center mt-10">
          خطا در دریافت اطلاعات
        </h1>
        {error.data}
      </Container>
    );
  }
}

export default ProjectPage;
