"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 { useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import MainProjectCard from "@/components/projects/MainProjectCard";
import { useTranslation } from "react-i18next";

function FailedProject() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request } = useAxios();
  const searchParams = useSearchParams();
  const projectId = searchParams.get("projectId");

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

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

  useEffect(() => {
    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);
      }
    };
    fetchAd();
    fetchStates();
  }, []);

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

  const payHandler = async () => {
    try {
      const response = await request<{ authority?: string; type?: string }>(
        "POST",
        "/projects/initiate-payment-web",
        {
          item_name: project?.project_type,
          projectId: projectId,
        }
      );
      if (response.type === "free") {
        router.push("/settings/workroom");
      } else {
        const authority = response.authority;
        const paymentUrl = `https://www.zarinpal.com/pg/StartPay/${authority}`;
        router.push(paymentUrl);
      }
    } catch (error: unknown) {
      console.log(error);
    }
  };

  return (
    <Container>
      <h6 className="font-bold md:text-xl text-lg text-center mt-2 line-clamp-2 mb-4 text-[#FF0000] ">
        {t("academy.payment.failed")}
      </h6>
      <div className="flex flex-col items-center text-sm">
        <Image
          width={50}
          height={50}
          alt={t("academy.payment.verifyIconAlt")}
          src={`/images/icons/failed.svg`}
          className="pb-1 mb-5"
        />
        <span>{t("academy.payment.failedHint")}</span>
        <span>{t("academy.payment.completePayment")}</span>
      </div>
      <div className="px-4 w-full text-sm md:text-md font-semibold mt-10">
        {project && <MainProjectCard project={project} />}
        <div className="flex flex-col items-center gap-4 mt-4">
          <RoundedDiv className="p-2 w-full">
            {getDisplayTypeLabel(project?.project_type)}:{" "}
            {Number(price).toLocaleString()} {t("settings.toman")}
          </RoundedDiv>
          <RoundedDiv className="p-2 w-full">
            {t("academy.payment.payableAmount", {
              price: Number(price).toLocaleString(),
            })}
          </RoundedDiv>
          <RoundedButton
            onClick={() => {
              payHandler();
            }}
            variant="primary"
            className="w-32 h-9"
          >
            {t("academy.payment.retry")}
          </RoundedButton>
        </div>
      </div>
    </Container>
  );
}

export default FailedProject;
