"use client";

import Container from "@/components/elements/Container";
import MainProjectCard from "@/components/projects/MainProjectCard";
import ProjectRequestForm from "@/components/projects/ProjectPage/ProjectRequestForm";
import ProjectRequests from "@/components/projects/ProjectPage/ProjectRequests";
import PageLoader from "@/components/ui/PageLoader";
import useAxios from "@/hooks/useAxios";
import { Project, IProjectRequest, ProjectRole } from "@/types/types";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

export default function ProjectDetailClient({ id }: { id: string }) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [project, setProject] = useState<Project | null>(null);
  const [projectRequests, setProjectRequests] = useState<IProjectRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [selectedRoleId, setSelectedRoleId] = useState<string | null>(null);

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

    const loadProject = async () => {
      setLoading(true);
      setError(false);
      try {
        const response = await request<{
          project: Project;
          projectRequests?: IProjectRequest[];
        }>("GET", `/projects/get/web/${id}`, null, { noToast: true });
        if (!cancelled) {
          const loaded = response?.project ?? null;
          setProject(loaded);
          setProjectRequests(response?.projectRequests ?? []);
          if (loaded?.roles?.length) {
            setSelectedRoleId(loaded.roles[0]._id);
          }
        }
      } catch {
        if (!cancelled) setError(true);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

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

  const selectedRole: ProjectRole | null = useMemo(() => {
    if (!project?.roles?.length) return null;
    return (
      project.roles.find((r) => r._id === selectedRoleId) ||
      project.roles[0] ||
      null
    );
  }, [project, selectedRoleId]);

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

  if (error || !project) {
    return (
      <Container>
        <p className="py-20 text-center text-neutral-500">
          {t("projects.notFound")}
        </p>
      </Container>
    );
  }

  return (
    <Container className="pb-28">
      <MainProjectCard
        project={project}
        full
        borderless
        selectedRoleId={selectedRoleId}
        onRoleSelect={setSelectedRoleId}
      />

      {selectedRole ? (
        <div className="mt-2 rounded-2xl border border-border-secondary-light p-3 text-xs dark:border-border-secondary-dark">
          <p className="font-bold">{selectedRole.expertise}</p>
          {selectedRole.sub_expertise?.length ? (
            <p className="mt-1 text-neutral-500">
              {selectedRole.sub_expertise.join(" _ ")}
            </p>
          ) : null}
          {(selectedRole.height_min != null ||
            selectedRole.height_max != null) && (
            <p className="mt-1">
              {t("filters.heightCm")}: {selectedRole.height_min ?? "—"} -{" "}
              {selectedRole.height_max ?? "—"}
            </p>
          )}
          {(selectedRole.weight_min != null ||
            selectedRole.weight_max != null) && (
            <p className="mt-1">
              {t("filters.weightKg")}: {selectedRole.weight_min ?? "—"} -{" "}
              {selectedRole.weight_max ?? "—"}
            </p>
          )}
          <p className="mt-1">
            {t("projects.newProject.fields.headcount")}:{" "}
            {selectedRole.number_of_person || 1}
          </p>
        </div>
      ) : null}

      {projectRequests.length > 0 ? (
        <div className="mt-4">
          <p className="mb-2 text-center text-xs font-semibold md:text-sm">
            {t("projects.requestUsersTitle")}
          </p>
          <ProjectRequests projectRequests={projectRequests} />
        </div>
      ) : null}

      <ProjectRequestForm
        projectId={id}
        creatorId={
          (project as Project & { creator_id?: string }).creator_id ||
          project.creator?._id
        }
        selectedRole={selectedRole}
        portfolioRequired={Boolean(selectedRole?.portfolio_required)}
      />
    </Container>
  );
}
