/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedDiv from "@/components/elements/RoundedDiv";
import { BASE_URL } from "@/components/main/BaseUrl";
import UserInfo from "@/components/main/UserInfo";
import PageTitle from "@/components/settings/PageTitle";
import useAxios from "@/hooks/useAxios";
import { IOfferType, User } from "@/types/types";
import axios from "axios";
import { useFormik } from "formik";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React, { useState, useEffect } from "react";
import toast from "react-hot-toast";
import Cookies from "js-cookie";
import * as Yup from "yup";



const validationSchema = Yup.object({
  selectedType: Yup.string().required(" انتخاب کردن نوع درخواست الزامی است"),
});

interface ITicketChatProps {
  params: Promise<{ id: string; title: string }>;
}

function TicketChat({ params }: ITicketChatProps) {
  const resolvedParams = React.use(params);
  const { request } = useAxios();
  const { id } = resolvedParams;
  const router = useRouter();

  const [userDetail, setUserDetail] = useState<User>();
  const [selectedType, setSelectedType] = useState("normal");
  const [typeList, setTypeList] = useState<IOfferType[] | null>(null);
  const [hasUsedFreeOffer, setHasUsedFreeOffer] = useState(false);

  useEffect(() => {
    const fetchUser = async () => {
      const response = await request<{ user: User }>(
        "GET",
        `/users/get?user_id=${id}`
      );
      setUserDetail(response?.user);
      setHasUsedFreeOffer(response?.user?.hasUsedFreeOffer || false);
    };
    fetchUser();
  }, [id]);

  const fetchOfferTypes = async () => {
    try {
      const response = await request<{ offerTypes: IOfferType[] }>(
        "GET",
        "/offers/types"
      );
      setTypeList(response?.offerTypes || null);
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    fetchOfferTypes();
  }, []);

  const formik = useFormik({
    initialValues: {
      selectedType: "normal",
    },
    validationSchema,
    onSubmit: async (values, { setSubmitting }) => {
      if (values.selectedType === "free" && hasUsedFreeOffer) {
        toast.error("شما قبلاً از درخواست رایگان استفاده کرده‌اید!");
        return;
      }

      const getToken = (): string => {
        if (typeof window !== "undefined") {
          const token = Cookies.get("token");
          return token ? `Bearer ${token}` : "";
        }
        return "";
      };

      try {
        const response = await axios.post(`${BASE_URL}/offers/initiate-payment-web`, {
             offerType: values.selectedType,
             receiverId: id,
           }, 
           {
             headers: {
               Authorization: getToken(), // ✅ اضافه شدن توکن به هدر
               "Content-Type": "application/json", // اختیاری ولی بهتره باشه
             },
           }
         );
         
           const data: { authority?: string; offerId?: string; type?: string } = response.data;
         
           console.log("Authority:", data.authority);
           console.log("Response:", response);
           if (values.selectedType === "free") {
             toast.success("درخواست رایگان شما ثبت شد!");
             setHasUsedFreeOffer(true);
             router.push(`/offer/payment/success?userId=${id}`);
           } 
           
           
           else if (data.authority) {
             const paymentUrl = `https://www.zarinpal.com/pg/StartPay/${data.authority}`;
             console.log("Redirecting to:", paymentUrl);
             window.open(paymentUrl, "_blank");
           } else {
             toast.error("خطا در دریافت اطلاعات پرداخت");
           }
           
     
        
  
      } catch (err: any) {
        console.error("Payment initiation error:", err);
        toast.error(err?.response?.data?.error || "خطا در شروع پرداخت");
      } finally {
        setSubmitting(false);
      }
    },
  }
);

  return (
    <Container>
      <div className="mx-3 mb-10">

      <PageTitle>پرداخت</PageTitle>
      <p className="text-center">
        شما فقط 1 بار می‌توانید درخواست رایگان ثبت کنید
      </p>
      <form
        className="flex flex-col gap-2 w-full items-center text-sm"
        onSubmit={formik.handleSubmit}
      >
        {typeList?.map((item: IOfferType) => {
          const isFree = item.name === "free";
          const isDisabled = isFree && hasUsedFreeOffer;

          return (
            <div
              onClick={() => {
                if (!isDisabled) {
                  setSelectedType(item?.name);
                  formik.setFieldValue("selectedType", item?.name);
                }
              }}
              className="w-full flex flex-col items-center max-w-md mt-8 gap-4 cursor-pointer"
              key={item?._id}
            >
              <div className="flex items-end justify-between w-full">
                <UserInfo
                  first_name={userDetail?.first_name}
                  is_verified={userDetail?.is_verified}
                  profile_image={userDetail?.profile_image}
                  user_level={userDetail?.user_level}
                  last_name={userDetail?.last_name}
                  user_name={userDetail?.user_name}
                  noLink
                />
                <div className="flex items-center justify-center gap-0.5">
                  <span>{userDetail?.user_score || "0"}</span>
                  <Image
                    width={21}
                    height={21}
                    alt={"verify icon"}
                    src={`/images/icons/medal-star.svg`}
                    className="pb-1"
                  />
                </div>
                <div className="flex items-center gap-0.5">
                  <span>{userDetail?.rate || "0"}</span>
                  <Image
                    width={21}
                    height={21}
                    alt={"verify icon"}
                    src={`/images/icons/star1.svg`}
                    className="pb-1"
                  />
                </div>
              </div>
              <RoundedDiv
                className={`w-full max-w-full p-2 ${
                  selectedType === item?.name ? "bg-[#FC8EAC]" : ""
                } ${isDisabled ? "opacity-50 cursor-not-allowed" : ""}`}
              >
                {item.name === "normal"
                  ? "درخواست همکاری"
                  : item.name === "free"
                  ? "ثبت درخواست رایگان"
                  : item.name === "special"
                  ? "نمایش با آیکون ویژه"
                  : "نمایش با رنگ پس زمینه متفاوت"}
                {item.price !== 0
                  ? ": " + Number(item.price).toLocaleString() + "تومان"
                  : ""}
              </RoundedDiv>
            </div>
          );
        })}

        <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
          ثبت درخواست
        </RoundedButton>
      </form>
      </div>
    </Container>
  );
}

export default TicketChat;
