"use client";

import Container from "@/components/elements/Container";
import { IAdvertising, IAdvertisingType } from "@/types/types";
import useAxios from "@/hooks/useAxios";
import React, { useEffect, useState } from "react";
import MainBillboardCard from "@/components/billboards/MainBillboardCard/MainBillboardCard";
import RoundedDiv from "@/components/elements/RoundedDiv";
import RoundedButton from "@/components/elements/RoundedButton";
import { useRouter } from "next/navigation";

interface IBillboardProps {
  params: Promise<{ id: string }>;
}

function BillboardPayment({ params }: IBillboardProps) {
  const resolvedParams = React.use(params);
  const router = useRouter();
  const { request } = useAxios();
  const { id } = resolvedParams;
  const [advertising, setAdvertising] = useState<IAdvertising>();
  const [typeList, setTypeList] = useState<IAdvertisingType[] | null>(null);
  const [price, setPrice] = useState("");
  useEffect(() => {
    const fetchAd = async () => {
      const response = await request<{ advertising: IAdvertising }>(
        "GET",
        `/advertising/get/web/${id}`
      );
      setAdvertising(response?.advertising);
    };
    const fetchStates = async () => {
      try {
        const response = await request<{
          advertisingTypes: IAdvertisingType[];
        }>("GET", "/advertising/types");
        setTypeList(response?.advertisingTypes || null);
      } catch (err) {
        console.log(err);
      }
    };
    fetchAd();
    fetchStates();
  }, []);

  const payHandler = async () => {
    try {
      const response = await request<{ authority?: string }>(
        "POST",
        "/advertising/initiate-payment-web",
        {
          item_name: advertising?.type, // Pass advertisingId to initiate payment
          advertisingId: id,
          showDiscount: advertising?.showDiscount,
        }
      );

      console.log(advertising?.type);
      

      if (advertising?.type === "free") {
        router.push("/settings/my-billboards");
      } 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);
    }
  };

  useEffect(() => {
    if (advertising?.type && typeList) {
      const foundType = typeList.find((item) => item.name === advertising.type);
      if (foundType) {
        setPrice(String(foundType.price)); // فرض بر اینکه price عددی است و نیاز به تبدیل به رشته دارد
      }
    }
  }, [advertising, typeList]);

  return (
    <Container>
      <h6 className="font-bold md:text-xl text-lg text-center mt-2 line-clamp-2 mb-4 text-text-blue-light dark:text-text-blue-dark">
        پرداخت
      </h6>
      <div className="px-4 w-full text-sm md:text-md font-semibold mt-10">
        {advertising && <MainBillboardCard billboard={advertising} />}
        <div className="flex flex-col items-center gap-4 mt-4">
          <RoundedDiv className="p-2 w-full">
            {advertising?.type === "special"
              ? "ویژه"
              : advertising?.type === "normal"
              ? "نمایش ساده"
              : advertising?.type === "free"
              ? "رایگان"
              : "برجسته"}
            : {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 BillboardPayment;
