// utils/campaignHelpers.ts
import { calculateDuration, normalizePrice } from "../datehelpers";

export interface CampaignAdvert {
  event_id: number;
  startDate: string;
  endDate: string;
  price: number;
  geo_price_level: number;
}

export interface CampaignPayload {
  media_type: string;
  advert_type: string;
  advert_redirect_url: string;
  user_notes: string;
  adverts: CampaignAdvert[];
  media_file?: File;
  stripe_session_id?: string;
  payment_amount?: number;
  discount_amount?: number;
  final_amount?: number;
  wallet_discount?: number;
  stripe_discount?: number;
  coupon_code?: string;
}

/**
 * Calculate total price from selected events
 */
export const calculateTotalPriceFromEvents = (events: any[]): number => {
  return events.reduce((total, event) => {
    console.log("calculateTotalPriceFromEvents event", event.price);
    const duration = calculateDuration(event.startDate, event.endDate);
    const pricePerDay = normalizePrice(event.price || 1);
    console.log("calculateTotalPriceFromEvents pricePerDay", pricePerDay);
    console.log("calculateTotalPriceFromEvents duration", duration);
    console.log("calculateTotalPriceFromEvents total", total);
    console.log(
      "calculateTotalPriceFromEvents total + duration * pricePerDay",
      total + duration * pricePerDay
    );
    // return total + duration * pricePerDay;
    return pricePerDay;
  }, 0);
};

/**
 * Send campaign data to Nest.js backend after successful payment
 */
export const sendCampaignToBackend = async (
  campaignData: CampaignPayload,
  token: string
): Promise<{ success: boolean; data?: any; error?: string }> => {
  try {
    const formData = new FormData();

    // Add campaign fields
    formData.append("media_type", campaignData.media_type);
    formData.append("advert_type", campaignData.advert_type);
    formData.append(
      "advert_redirect_url",
      campaignData.advert_redirect_url || ""
    );
    formData.append("user_notes", campaignData.user_notes || "");

    // Add adverts as JSON string
    formData.append("adverts", JSON.stringify(campaignData.adverts));

    // Add Stripe session ID if provided
    if (campaignData.stripe_session_id) {
      formData.append("stripe_session_id", campaignData.stripe_session_id);
    }

    // Add payment amount if provided
    if (campaignData.payment_amount !== undefined) {
      formData.append("payment_amount", campaignData.payment_amount.toString());
    }

    // Add discount amount if provided
    if (campaignData.discount_amount !== undefined) {
      formData.append(
        "discount_amount",
        campaignData.discount_amount.toString()
      );
    }

    // Add final amount if provided
    if (campaignData.final_amount !== undefined) {
      formData.append("final_amount", campaignData.final_amount.toString());
    }

    // Add wallet discount if provided
    if (campaignData.wallet_discount !== undefined) {
      formData.append(
        "wallet_discount",
        campaignData.wallet_discount.toString()
      );
    }

    // Add Stripe promo code discount if provided
    if (campaignData.stripe_discount !== undefined) {
      formData.append(
        "stripe_discount",
        campaignData.stripe_discount.toString()
      );
    }

    // Add coupon code if provided
    if (campaignData.coupon_code) {
      formData.append("coupon_code", campaignData.coupon_code);
    }

    // Add media file if exists
    if (campaignData.media_file) {
      formData.append("media", campaignData.media_file);
    }

    const apiUrl = process.env.NEXT_PUBLIC_API_URL_New;

    const response = await fetch(`${apiUrl}/sep-user-campaign/create`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
    });

    console.log("formData", formData);
    console.log("token", token);
    console.log("apiUrl", apiUrl);
    console.log("response", response);
    if (!response.ok) {
      const errorData = await response
        .json()
        .catch(() => ({ message: "Unknown error" }));

      // Handle validation errors from backend
      if (errorData.errors && typeof errorData.errors === "object") {
        const errorMessages = Object.values(errorData.errors).join(", ");
        throw new Error(
          errorMessages ||
            errorData.message ||
            `HTTP error! status: ${response.status}`
        );
      }

      throw new Error(
        errorData.message || `HTTP error! status: ${response.status}`
      );
    }

    const data = await response.json();

    // Check if backend returned an error response even with 200 status
    if (data.status && data.status !== 201 && data.status !== 200) {
      throw new Error(data.message || "Failed to create campaign");
    }

    return { success: true, data };
  } catch (error: any) {
    console.error("Error sending campaign to backend:", error);
    return {
      success: false,
      error: error.message || "Failed to create campaign",
    };
  }
};

/**
 * Prepare campaign data from Redux state
 */
export const prepareCampaignData = (
  campaignForm: any,
  selectedEvents: any[],
  mediaFile?: File,
  stripeSessionId?: string,
  paymentAmount?: number,
  discountAmount?: number,
  finalAmount?: number,
  walletDiscount?: number,
  stripeDiscount?: number,
  couponCode?: string
): CampaignPayload => {
  console.log("paymentAmount", paymentAmount);
  console.log("discountAmount", discountAmount);
  console.log("finalAmount", finalAmount);
  console.log("walletDiscount", walletDiscount);
  console.log("stripeDiscount", stripeDiscount);
  console.log("couponCode", couponCode);
  const adverts: CampaignAdvert[] = selectedEvents.map((event) => ({
    event_id: parseInt(event.event_id),
    startDate: event.startDate,
    endDate: event.endDate,
    price: normalizePrice(event.price || 1),
    geo_price_level: event.geo_price_level || 0,
  }));

  return {
    media_type: campaignForm.media_type,
    advert_type: campaignForm.advert_type,
    advert_redirect_url: campaignForm.advert_redirect_url || "",
    user_notes: campaignForm.user_notes || "",
    adverts,
    media_file: mediaFile,
    stripe_session_id: stripeSessionId,
    payment_amount: paymentAmount,
    discount_amount: discountAmount,
    final_amount: finalAmount,
    wallet_discount: walletDiscount,
    stripe_discount: stripeDiscount,
    coupon_code: couponCode,
  };
};

export const getDynamicDimensions = (baseWidth: number, baseHeight: number) => {
  const width = Math.round(baseWidth) * 3;
  const height = Math.round(baseHeight) * 3;
  return { width, height };
};
export const getRequiredDimensionsForSize = (size: string) => {
  switch (size) {
    case "medium":
      return getDynamicDimensions(300, 250);
    case "large":
      return getDynamicDimensions(350, 280);
    case "pop under":
      return getDynamicDimensions(720, 300);
    default:
      return getDynamicDimensions(720, 300);
  }
};
export const getDisplayDimensions = (dimensions: string) => {
  if (!dimensions) return dimensions;

  const matches = dimensions.match(/(\d+)\s*x\s*(\d+)/);
  if (!matches) return dimensions;

  const baseWidth = parseInt(matches[1]);
  const baseHeight = parseInt(matches[2]);

  const dynamicDims = getDynamicDimensions(baseWidth, baseHeight);
  return `${dynamicDims.width} x ${dynamicDims.height} px`;
};
export const formatAspectRatio = (width: number, height: number): string => {
  // Find greatest common divisor
  const gcd = (a: number, b: number): number => {
    return b === 0 ? a : gcd(b, a % b);
  };

  const divisor = gcd(width, height);
  return `${width / divisor} / ${height / divisor}`;
};
