import { getOtherAttributeImageUrl } from "@/hooks/useImageUrl";
import axios from "axios";
import {
  Advertisement,
  AdvertisementsData,
  PlacementKey,
} from "../../../types/advertisements";
import { getLocation, getSavedLocation } from "../utils/location";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;

export async function fetchProductRecommendations(
  token: string,
  locale: string,
) {
  try {
    const location = getSavedLocation();
    let url = `${API_BASE_URL}/home/products`;
    if (location) {
      url += `?latitude=${location.lat}&longitude=${location.lng}`;
    }
    const { data } = await axios.get(url, {
      headers: {
        "Content-Type": "application/json",
        "Accept-Language": locale,
        Authorization: "Bearer " + token,
      },
    });

    return data;
  } catch (error) {
    throw error;
  }
}

export async function getProductsByCategory(
  token: string,
  categoryName: string,
  locale: string,
) {
  try {
    const { data } = await fetchProductRecommendations(token, locale);
    const category =
      data[categoryName] ||
      Object.values(data).find(
        (cat: any) =>
          "slug" in cat &&
          cat.slug === categoryName.toLowerCase().replace(/\s+/g, "-"),
      );

    if (!category?.products?.length) {
      return [];
    }

    return category.products.map((product: any) => ({
      id: product.productId,
      title: product.title || "Untitled Product",
      description: product.description || "",
      price: product.price,
      time: "Recently added",
      location: null,
      imageUrl: getOtherAttributeImageUrl(product),
      slug: category.slug || categoryName.toLowerCase().replace(/\s+/g, "-"),
    }));
  } catch (error) {
    throw error;
  }
}

export async function getAllProductCategories(token: string, locale: string) {
  try {
    const { data } = await fetchProductRecommendations(token, locale);

    let sections = Object.entries(data).map(([categoryName, categoryData]) => {
      const products = (categoryData as any).products || [];
      const get_slug = (categoryData as any).slug || "";
      return {
        title: categoryName,
        //slug: categoryName.toLowerCase().replace(/\s+/g, "-"),
        slug: get_slug,

        items: products.map((product: any) => {
          return {
            id: product.productId,
            title: product.title || "Untitled Product",
            description: product.description || "",
            price: product.price,
            time: product.createdAt || "Recently added",
            location: product?.location ?? null,
            imageUrl: getOtherAttributeImageUrl(product),
            slug: product.productId,
            isWishlisted: product.isWishlisted || false,
            totalNumberOfViews: product.totalNumberOfViews || 0,
            distance: product.distance,
            createdAt: product.createdAt,
            creator: product.creator
              ? {
                  id: product.creator._id,
                  name: [
                    product.creator.first_name,
                    product.creator.middle_name,
                    product.creator.last_name,
                  ]
                    .filter(Boolean)
                    .join(" "),
                  email: product.creator.email,
                  profileImage: product.creator.profile_image,
                }
              : null,
            isOtherAttribute: product?.otherAttribute ? true : false,
            otherAttribute: product?.otherAttribute,
            productType: product?.otherAttribute
              ? product?.otherAttribute.valueType
              : "product",
          };
        }),
      };
    });

    const freshRecIndex = sections.findIndex((section) =>
      section.title.toLowerCase().includes("fresh recommendations"),
    );

    let freshRecSection = null;
    if (freshRecIndex !== -1) {
      freshRecSection = sections.splice(freshRecIndex, 1)[0];
    }
    const resultSections = [];
    if (freshRecSection) {
      resultSections.push(freshRecSection);
    }

    resultSections.push(...sections);
    const featuredSection =
      resultSections.length > 0
        ? {
            ...resultSections[0],
            isFeatured: true,
            slug: resultSections[0].slug,
          }
        : null;

    return {
      sections: resultSections.slice(1),
      featuredSection,
    };
  } catch (error) {
    throw error;
  }
}

export async function getAdvertisements(
  token: string,
  singleAd?: PlacementKey,
): Promise<{
  status: boolean;
  message: string;
  success_type: string;
  data: AdvertisementsData;
}> {
  try {
    const url = singleAd
      ? `${API_BASE_URL}/home/advertisement/${singleAd}/type`
      : `${API_BASE_URL}/home/advertisements`;
    const headers = {
      Authorization: `Bearer ${token}`,
    };
    const result = await axios.get(url, {
      headers,
    });

    const data = result.data.data as AdvertisementsData;

    return {
      status: true,
      message: "Advertisements fetched successfully",
      success_type: "success",
      data,
    };
  } catch (error) {
    throw error;
  }
}

export async function getSingleAd(
  token: string,
  singleAd: PlacementKey,
): Promise<{
  status: boolean;
  message: string;
  success_type: string;
  data: Advertisement[];
}> {
  try {
    const url = `${API_BASE_URL}/home/advertisement/${singleAd}/type`;
    const headers = {
      Authorization: `Bearer ${token}`,
    };
    const result = await axios.get(url, {
      headers,
    });

    const data = result?.data?.data?.advertisements as Advertisement[];

    return {
      status: true,
      message: "Advertisements fetched successfully",
      success_type: "success",
      data,
    };
  } catch (error) {
    throw error;
  }
}
