/* eslint-disable @typescript-eslint/no-explicit-any */
import { dataURLtoBlob } from "@/helpers/helpers";
import { BillboardFormData } from "@/contexts/BillboardFormContext";

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

type RequestFn = <T>(
  method: "GET" | "POST" | "PUT" | "DELETE",
  url: string,
  data?: unknown
) => Promise<T>;

export async function submitBillboard(
  formData: BillboardFormData,
  isEditing: boolean,
  request: RequestFn
): Promise<{ id: string } | null> {
  const {
    adsTitle,
    categoryId,
    description,
    stateId,
    cityId,
    neighbourhood,
    address,
    markerCoordinate,
    services,
    selectedFeatures,
    landline,
    mobile,
    telegram,
    whatsapp,
    instagram,
    saveData,
    images,
  } = formData;

  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));
  }

  data.append("type", isEditing ? formData.selectedType || "free" : "free");

  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`
      );
    }
  });

  if (isEditing) {
    await request<{ id: string; message: string }>(
      "POST",
      `/advertising/edit/${formData?._id}`,
      data
    );
    return null;
  }

  const response = await request<CreateAdvertisingResponse>(
    "POST",
    "/advertising/create",
    data
  );

  await request("POST", "/advertising/initiate-payment-web", {
    item_name: "free",
    advertisingId: response.data.id,
    showDiscount: false,
  });

  return { id: response.data.id };
}
