"use client";

import Container from "@/components/elements/Container";
import MainProjectCard from "@/components/projects/MainProjectCard";
import ProjectRequestForm from "@/components/projects/ProjectPage/ProjectRequestForm";
import PageLoader from "@/components/ui/PageLoader";
import useAxios from "@/hooks/useAxios";
import { Project } from "@/types/types";
import { useEffect, useState } from "react";

export default function ProjectDetailClient({ id }: { id: string }) {
  const { request } = useAxios();
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    let cancelled = false;

    const loadProject = async () => {
      setLoading(true);
      setError(false);
      try {
        const response = await request<{ project: Project }>(
          "GET",
          `/projects/get/web/${id}`,
          null,
          { noToast: true }
        );
        if (!cancelled) setProject(response?.project ?? null);
      } catch {
        if (!cancelled) setError(true);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    void loadProject();
    return () => {
      cancelled = true;
    };
  }, [id, request]);

  if (loading) return <PageLoader className="min-h-[50vh]" />;

  if (error || !project) {
    return (
      <Container>
        <p className="py-20 text-center text-neutral-500">پروژه یافت نشد.</p>
      </Container>
    );
  }

  return (
    <Container className="pb-28">
      <MainProjectCard project={project} full />
      <ProjectRequestForm
        projectId={id}
        creatorId={
          (project as Project & { creator_id?: string }).creator_id ||
          project.creator?._id
        }
      />
    </Container>
  );
}
