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

import RoundedButton from "@/components/elements/RoundedButton";
import { useFormik } from "formik";
import * as Yup from "yup";

import { useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import { IAdvertisingType } from "@/types/types";
import { sampleAds, sampleAdsHighlight, sampleAdsSpecial } from "@/constants";
import RoundedDiv from "@/components/elements/RoundedDiv";
import { useRouter } from "next/navigation";
import MainBillboardCard from "../MainBillboardCard/MainBillboardCard";
import { dataURLtoBlob } from "@/helpers/helpers";
import { useBillboardForm } from "@/contexts/BillboardFormContext";

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

interface CreateAdvertisingResponse {
  success: boolean;
  message: string;
  data: {
    id: string;
  };
}

const Step5 = () => {
  const router = useRouter();
  const { request } = useAxios();
  const { formData, updateForm, isEditing } = useBillboardForm();
  const [selectedType, setSelectedType] = useState("normal");
  const [showDiscount, setShowDiscount] = useState<boolean>(false); // New state for checkbox
  const [typeList, setTypeList] = useState<IAdvertisingType[] | null>(null);

  const {
    adsTitle,
    categoryId,
    description,
    stateId,
    cityId,
    neighbourhood,
    address,
    markerCoordinate,
    services,
    selectedFeatures,
    landline,
    mobile,
    telegram,
    whatsapp,
    instagram,
    saveData,
    images,
  } = formData;

  const toggleCheckBox = () => {
    setShowDiscount(!showDiscount);
  };

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

  const formik = useFormik({
    initialValues: {
      selectedType: formData.selectedType || "",
    },
    validationSchema,
    onSubmit: async (values) => {
      updateForm(values);

      const data = new FormData();
      data.append("title", adsTitle);
      data.append("category", categoryId);
      if (description) {
        data.append("description", description);
      }
      data.append("province", stateId ? stateId : "");
      data.append("city", cityId ? cityId : "");
      if (neighbourhood) {
        data.append("neighbourhood", neighbourhood);
      }
      if (address) {
        data.append("address", address);
      }
      if (markerCoordinate) {
        data.append("lat", markerCoordinate[0]);
        data.append("lng", markerCoordinate[1]);
      }
      data.append("services", JSON.stringify(services));
      data.append("features", JSON.stringify(selectedFeatures));
      if (landline) {
        data.append("contactInfo[phone]", landline);
      }
      if (mobile) {
        data.append("contactInfo[mobile]", mobile);
      }
      if (telegram) {
        data.append("contactInfo[telegramLink]", telegram);
      }
      if (whatsapp) {
        data.append("contactInfo[whatsappNumber]", whatsapp);
      }
      if (instagram) {
        data.append("contactInfo[instagramLink]", instagram);
      }
      if (saveData !== null && typeof saveData === "boolean") {
        data.append("contactInfo[saveInfoForNextAds]", String(saveData));
      }

      if (showDiscount !== null && typeof showDiscount === "boolean") {
        data.append("showDiscount", String(showDiscount)); // تغییر اینجا بود!
      }
      data.append("type", selectedType);

      const mostDiscountPercentage =
        services.length > 0
          ? services.reduce<number>((max, service) => {
              // بررسی و تبدیل مقدار discountPercentage به عدد
              const discount =
                typeof service.discountPercentage === "number"
                  ? service.discountPercentage
                  : 0;

              return discount > max ? discount : max;
            }, 0)
          : 0;

      if (mostDiscountPercentage) {
        data.append("mostDiscountPercentage", String(mostDiscountPercentage));
      }

      // const modifiedServices = services.map((service) => ({
      //   ...service,
      //   image: "", // جایگزین کردن مقدار image با یک رشته خالی
      // }));

      // data.append("services", JSON.stringify(modifiedServices));

      // data.append("services", JSON.stringify(services));

      // افزودن تصاویر به فرم داده‌ها
      images?.forEach((image) => {
        if (typeof image === "string" && image.startsWith("/advertising/")) {
          data.append("existingImages[]", image);
        } else {
          const blob = dataURLtoBlob(image); // تبدیل Base64 به Blob
          data.append("images", blob);
        }
      });

      // اضافه کردن تصاویر خدمات به فرم داده
      services.forEach((service) => {
        if (
          typeof service.image === "string" &&
          service.image.startsWith("/services/")
        ) {
          data.append(`existingServiceImages[${service.id}]`, service.image);
        } else if (service.image) {
          const blob = dataURLtoBlob(service.image); // تبدیل Base64 به Blob
          data.append(
            `serviceImages[${service.id}]`,
            blob,
            `service-${service.id}.jpg`
          );
        }
      });
      try {
        if (isEditing) {
          await request<{ id: string; message: string }>(
            "POST",
            `/advertising/edit/${formData?._id}`,
            data
          );
          localStorage.removeItem("billboardForm");
          router.push(`/settings/my-billboards`);
        } else {
          const response = await request<CreateAdvertisingResponse>(
            "POST",
            "/advertising/create",
            data
          );
          localStorage.removeItem("billboardForm");
          // console.log(response?.data?.id);
          
          router.push(`/billboards/new/${response.data.id}`);
        }
      } catch (err: any) {
        console.log("Unhandled error:", err?.message);
      }
    },
  });
  useEffect(() => {
    if (isEditing && formik.values.selectedType) {
      formik.submitForm();
    }
  }, [isEditing, formik.values.selectedType]);

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex flex-col gap-2 w-full items-center text-sm"
    >
      <h6 className="font-bold text-xl mb-2">نوع نمایش</h6>
      <p>نوع نمایش بیلبورد خود برای کاربران را مشخص کنید</p>
      <div className="flex items-center gap-2 mt-10">
        <input
          className="scale-125"
          type="checkbox"
          onChange={toggleCheckBox}
        />
        <span className="text-xs font-bold">
          نمایش درصد تخفیف (+20،000 تومان)
        </span>
      </div>
      {typeList?.map((item: IAdvertisingType) => {
        return (
          <div
            onClick={() => {
              setSelectedType(item?.name);
              formik.setFieldValue("selectedType", item?.name);
            }}
            className="w-full flex flex-col items-center"
            key={item?._id}
          >
            <MainBillboardCard
              adStatus=""
              billboard={
                item?.name == "special"
                  ? sampleAdsSpecial
                  : item?.name == "highlight"
                  ? sampleAdsHighlight
                  : sampleAds
              }
            />
            <RoundedDiv
              className={`w-full max-w-full p-2 ${
                selectedType == item?.name ? "bg-[#FC8EAC]" : ""
              }`}
            >
              {item.name === "normal"
                ? "نمایش ساده"
                : item.name === "free"
                ? "نمایش ساده"
                : item.name === "special"
                ? "نمایش با آیکون ویژه"
                : "نمایش با رنگ پس زمینه متفاوت"}
              :
              {item.price !== 0
                ? !showDiscount
                  ? Number(item.price).toLocaleString() + "تومان"
                  : (Number(item.price) + 20000).toLocaleString() + "تومان"
                : " رایگان"}
            </RoundedDiv>
          </div>
        );
      })}
      {formik.touched.selectedType && formik.errors.selectedType && (
        <p className="text-red-500">{formik.errors.selectedType}</p>
      )}
      <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
        ثبت درخواست
      </RoundedButton>
    </form>
  );
};

export default Step5;
