"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";

function FailedProject() {
  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("");
  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)); // فرض بر اینکه 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, // Pass advertisingId to initiate payment
          projectId: projectId,
        }
      );
      if (response.type === "free") {
        router.push("/settings/workroom");
      } else {
        const authority = response.authority; // Get the payment authority
        const paymentUrl = `https://www.zarinpal.com/pg/StartPay/${authority}`; // Construct payment URL
        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] ">
        پرداخت ناموفق
      </h6>
      <div className="flex flex-col items-center text-sm">
        <Image
          width={50}
          height={50}
          alt={"verify icon"}
          src={`/images/icons/failed.svg`}
          className="pb-1 mb-5"
        />
        <span> پرداخت شما با خطا مواجه شد. </span>
        <span> برای تایید درخواست پرداخت خود را کامل کنید</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">
            {project?.project_type === "normal"
              ? "نمایش ساده"
              : project?.project_type === "force"
              ? "نمایش با برچسب فوری"
              : "نمایش با رنگ پس زمینه متفاوت"}
            : {Number(price).toLocaleString()} تومان
          </RoundedDiv>
          <RoundedDiv className="p-2 w-full">
            مبلغ قابل پرداخت: {Number(price).toLocaleString()} تومان
          </RoundedDiv>
          <RoundedButton
            onClick={() => {
              payHandler();
            }}
            className="w-32 h-9 !border-[#0C8002] text-[#0C8002]"
          >
            پرداخت مجدد
          </RoundedButton>
        </div>
      </div>
    </Container>
  );
}

export default FailedProject;
