/* 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, useMemo, 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 { selectionCardClass } from "@/lib/ui/buttonStyles";
import { useRouter } from "next/navigation";
import MainBillboardCard from "@/components/billboards/MainBillboardCard/MainBillboardCard";
import { dataURLtoBlob } from "@/helpers/helpers";
import { useBillboardForm } from "@/contexts/BillboardFormContext";
import { getBillboardDisplayTypeOptionLabel } from "@/lib/billboards/displayTypeLabel";
import { useTranslation } from "react-i18next";

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

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

  const validationSchema = useMemo(
    () =>
      Yup.object({
        selectedType: Yup.string().required(
          t("billboards.form.validation.displayTypeRequired")
        ),
      }),
    [t]
  );

  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) => {
              const discount =
                typeof service.discountPercentage === "number"
                  ? service.discountPercentage
                  : 0;

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

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

      images?.forEach((image) => {
        if (typeof image === "string" && image.startsWith("/advertising/")) {
          data.append("existingImages[]", image);
        } else {
          const blob = dataURLtoBlob(image);
          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);
          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");
          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">{t("billboards.displayTypeTitle")}</h6>
      <p>{t("billboards.displayTypeHint")}</p>
      <div className="flex items-center gap-2 mt-10">
        <input
          className="scale-125"
          type="checkbox"
          onChange={toggleCheckBox}
        />
        <span className="text-xs font-bold">{t("billboards.showDiscount")}</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={selectionCardClass(selectedType == item?.name)}
            >
              {getBillboardDisplayTypeOptionLabel(t, item.name)}:
              {item.price !== 0
                ? !showDiscount
                  ? Number(item.price).toLocaleString() + t("settings.toman")
                  : (Number(item.price) + 20000).toLocaleString() +
                    t("settings.toman")
                : ` ${t("billboards.free")}`}
            </RoundedDiv>
          </div>
        );
      })}
      {formik.touched.selectedType && formik.errors.selectedType && (
        <p className="text-red-500">{formik.errors.selectedType}</p>
      )}
      <RoundedButton type="submit" variant="primary" className="mt-4 px-8 py-2">
        {t("billboards.submitRequest")}
      </RoundedButton>
    </form>
  );
};

export default Step5;
