"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 MainProjectCard from "@/components/projects/MainProjectCard";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import toast from "react-hot-toast";

function FailedProject() {
  const { t } = useTranslation("common");
  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" || 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();
    void fetchStates();
  }, [projectId, request]);

  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;
        message?: string;
      }>(
        "POST",
        "/projects/initiate-payment-web",
        {
          item_name: project?.project_type || "normal",
          projectId: projectId,
        },
        { noToast: true }
      );
      if (response.type === "free") {
        window.location.href = `/projects/payment/success?projectId=${projectId}`;
      } else if (response.authority) {
        window.location.href = `https://www.zarinpal.com/pg/StartPay/${response.authority}`;
      } else {
        toast.error(response?.message || t("projects.payment.initFailed"));
      }
    } catch (error: unknown) {
      const axiosErr = error as { response?: { data?: { message?: string } } };
      toast.error(
        axiosErr?.response?.data?.message || t("projects.payment.initFailed")
      );
    }
  };

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

export default FailedProject;
