"use client";

import Container from "@/components/elements/Container";
import { IProjectType, Project } from "@/types/types";
import useAxios from "@/hooks/useAxios";
import React, { useEffect, useState } from "react";
import RoundedDiv from "@/components/elements/RoundedDiv";
import RoundedButton from "@/components/elements/RoundedButton";
import { useSearchParams } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import MainProjectCard from "@/components/projects/MainProjectCard";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function SuccessProject() {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const searchParams = useSearchParams();
  const projectId = searchParams.get("projectId");
  const paymentType = searchParams.get("type");

  const [project, setProject] = useState<Project>();
  const [typeList, setTypeList] = useState<IProjectType[] | null>(null);
  const [price, setPrice] = useState("");
  const [completionSubmitted, setCompletionSubmitted] = useState(false);

  const getDisplayTypeLabel = (projectType?: string) => {
    if (projectType === "normal" || projectType === "free") {
      return t("projects.newProject.displaySimple");
    }
    if (projectType === "force") {
      return t("projects.newProject.displayUrgent");
    }
    return t("projects.newProject.displayHighlight");
  };

  useEffect(() => {
    if (!projectId) return;
    const fetchAd = async () => {
      const response = await request<{ project: Project }>(
        "GET",
        `/projects/get/web/${projectId}`
      );
      setProject(response?.project);
    };
    const fetchStates = async () => {
      try {
        const response = await request<{ projectTypes: IProjectType[] }>(
          "GET",
          "/projects/types"
        );
        setTypeList(response?.projectTypes || null);
      } catch (err) {
        console.log(err);
      }
    };
    void fetchAd();
    if (!paymentType) void fetchStates();
  }, [projectId, request, paymentType]);

  useEffect(() => {
    if (project?.project_type && typeList) {
      const foundType = typeList.find(
        (item) => item.name === project.project_type
      );
      if (foundType) setPrice(String(foundType.price));
    }
  }, [project, typeList]);

  // پرداخت مرحله تکمیل پروژه: نظر و امتیازی که قبل از رفتن به درگاه ذخیره شده بود حالا ثبت می‌شود
  useEffect(() => {
    if (paymentType !== "completion" || !projectId || completionSubmitted) return;
    if (typeof window === "undefined") return;

    const key = `project-done-${projectId}`;
    const stashed = sessionStorage.getItem(key);
    if (!stashed) {
      setCompletionSubmitted(true);
      return;
    }

    const submitDone = async () => {
      try {
        const { comment, rate, user_id } = JSON.parse(stashed);
        const body: Record<string, unknown> = {
          project_id: projectId,
          comment,
          user_id,
        };
        if (rate) body.rate = rate;
        await request("POST", "/projects/done/web", body);
      } catch (err) {
        console.log(err);
      } finally {
        sessionStorage.removeItem(key);
        setCompletionSubmitted(true);
      }
    };
    void submitDone();
  }, [paymentType, projectId, completionSubmitted, request]);

  return (
    <LocalePageShell>
      <Container>
        <h6 className="mb-4 mt-2 line-clamp-2 text-center text-lg font-bold text-[#17A600] md:text-xl">
          {t("projects.payment.success")}
        </h6>
        <div className="flex flex-col items-center text-sm">
          <Image
            width={50}
            height={50}
            alt=""
            src={`/images/icons/success.svg`}
            className="mb-5 pb-1"
          />
        </div>
        <div className="mt-10 w-full px-4 text-sm font-semibold md:text-base">
          {project && <MainProjectCard project={project} />}
          <div className="mt-4 flex flex-col items-center gap-4">
            {!paymentType && (
              <RoundedDiv className="w-full p-2">
                {getDisplayTypeLabel(project?.project_type)}:{" "}
                {Number(price).toLocaleString()} {t("settings.toman")}
              </RoundedDiv>
            )}
            <p className="my-5">{t("projects.payment.reviewNotice")}</p>
            <Link href={"/settings/workroom"}>
              <RoundedButton variant="primary" className="h-9 w-32">
                {t("projects.payment.workroom")}
              </RoundedButton>
            </Link>
          </div>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default SuccessProject;
