"use server";
import axios from "axios";
import { getStoredLocale } from "../getLocale";

// Transform filter data to the new API format
function transformFilterData(data: any, filterOptions: any): any {
  // Input validation
  if (!data || typeof data !== "object") {
    throw new Error("Invalid data: data must be an object");
  }

  if (!data.title || typeof data.title !== "string") {
    throw new Error("Invalid data: title is required and must be a string");
  }

  if (!data.filters || typeof data.filters !== "object") {
    throw new Error("Invalid data: filters is required and must be an object");
  }

  const { title, filters, category } = data;

  // Ensure filterOptions exists and has default values
  const safeFilterOptions = filterOptions || {
    colors: [],
    conditions: [],
    fuels: [],
    brands: [],
    tags: [],
    dynamicAttributes: {},
    attributeIds: {},
  };

  // Transform attributes
  const attributes: any[] = [];

  // Handle colors
  if (
    filters.selectedColors &&
    filters.selectedColors.length > 0 &&
    safeFilterOptions.colors
  ) {
    const colorValues = safeFilterOptions.colors
      .filter(
        (color: any) => color && filters.selectedColors.includes(color.id)
      )
      .map((color: any) => ({
        key: color.id,
        value: color.label || color.value,
      }));

    if (colorValues.length > 0) {
      const colorAttributeId = safeFilterOptions.attributeIds?.color;
      if (!colorAttributeId) {
        // console.warn("Color attribute ID not found in filterOptions");
        return; // Skip this attribute if ID is missing
      }
      attributes.push({
        attributeId: colorAttributeId,
        name: "Color",
        values: colorValues,
      });
    }
  }

  // Handle conditions
  if (
    filters.selectedConditions &&
    filters.selectedConditions.length > 0 &&
    safeFilterOptions.conditions
  ) {
    const conditionValues = safeFilterOptions.conditions
      .filter(
        (condition: any) =>
          condition && filters.selectedConditions.includes(condition.id)
      )
      .map((condition: any) => ({
        key: condition.id,
        value: condition.value,
      }));

    if (conditionValues.length > 0) {
      const conditionAttributeId = safeFilterOptions.attributeIds?.condition;
      if (!conditionAttributeId) {
        // console.warn("Condition attribute ID not found in filterOptions");
        return; // Skip this attribute if ID is missing
      }
      attributes.push({
        attributeId: conditionAttributeId,
        name: "Condition",
        values: conditionValues,
      });
    }
  }

  // Handle fuels
  if (
    filters.selectedFuels &&
    filters.selectedFuels.length > 0 &&
    safeFilterOptions.fuels
  ) {
    const fuelValues = safeFilterOptions.fuels
      .filter((fuel: any) => fuel && filters.selectedFuels.includes(fuel.id))
      .map((fuel: any) => ({
        key: fuel.id,
        value: fuel.value,
      }));

    if (fuelValues.length > 0) {
      const fuelAttributeId = safeFilterOptions.attributeIds?.fuel;
      if (!fuelAttributeId) {
        // console.warn("Fuel attribute ID not found in filterOptions");
        return; // Skip this attribute if ID is missing
      }
      attributes.push({
        attributeId: fuelAttributeId,
        name: "Fuel",
        values: fuelValues,
      });
    }
  }

  // Handle dynamic attributes
  if (safeFilterOptions.dynamicAttributes) {
    Object.entries(safeFilterOptions.dynamicAttributes).forEach(
      ([uniqueKey, attr]: [string, any]) => {
        if (attr && attr.filterKey && attr.options) {
          const filterKey = attr.filterKey;
          const selectedValues = filters[filterKey] || [];

          if (selectedValues.length > 0) {
            const attributeValues = attr.options
              .filter(
                (option: any) => option && selectedValues.includes(option.id)
              )
              .map((option: any) => ({
                key: option.id,
                value: option.label || option.value,
              }));

            if (attributeValues.length > 0) {
              if (!attr.attributeId) {
                // console.warn(
                //   `Dynamic attribute ${uniqueKey} missing attributeId`
                // );
                return; // Skip this attribute if ID is missing
              }
              attributes.push({
                attributeId: attr.attributeId,
                name: attr.title,
                values: attributeValues,
              });
            }
          }
        }
      }
    );
  }

  // Handle brands as attribute
  if (
    filters.selectedBrands &&
    filters.selectedBrands.length > 0 &&
    safeFilterOptions.brands
  ) {
    const brandValues = safeFilterOptions.brands
      .filter(
        (brand: any) => brand && filters.selectedBrands.includes(brand.id)
      )
      .map((brand: any) => ({
        key: brand.id,
        value: brand.value,
      }));

    if (brandValues.length > 0) {
      const brandAttributeId = safeFilterOptions.attributeIds?.brand;
      if (!brandAttributeId) {
        // console.warn("Brand attribute ID not found in filterOptions");
      } else {
        attributes.push({
          attributeId: brandAttributeId,
          name: "brands",
          values: brandValues,
        });
      }
    }
  }

  // Handle tags as attribute
  if (
    filters.selectedTags &&
    filters.selectedTags.length > 0 &&
    safeFilterOptions.tags
  ) {
    const tagValues = safeFilterOptions.tags
      .filter((tag: any) => tag && filters.selectedTags.includes(tag.key))
      .map((tag: any) => ({
        key: tag.key,
        value: tag.value,
      }));

    if (tagValues.length > 0) {
      const tagAttributeId = safeFilterOptions.attributeIds?.tag;
      if (!tagAttributeId) {
        // console.warn("Tag attribute ID not found in filterOptions");
      } else {
        attributes.push({
          attributeId: tagAttributeId,
          name: "tags",
          values: tagValues,
        });
      }
    }
  }

  // Handle price range as attribute
  if (filters.priceRange && filters.priceRange.length === 2) {
    const priceValues = [
      { key: "min", value: filters.priceRange[0].toString() },
      { key: "max", value: filters.priceRange[1].toString() },
    ];

    const priceAttributeId = safeFilterOptions.attributeIds?.price;
    if (!priceAttributeId) {
      // console.warn("Price attribute ID not found in filterOptions");
    } else {
      attributes.push({
        attributeId: priceAttributeId,
        name: "price",
        values: priceValues,
      });
    }
  }

  // Determine category_type and category
  const category_type = "Product";
  const category_name = category || "fresh-recommendations";

  return {
    category_type,
    category: category_name,
    title,
    attributes,
  };
}

// Save Search
export async function saveSearch(
  data: any,
  token: string | null,
  filterOptions?: any
): Promise<any> {
  if (!token) {
    return {
      success: false,
      message: "Authentication token is required",
    };
  }

  try {
    // Enhanced validation
    // if (!data || typeof data !== 'object') {
    //   return { success: false, message: "Invalid data: data must be an object" };
    // }

    // if (!data.title || typeof data.title !== 'string' || data.title.trim().length === 0) {
    //   return { success: false, message: "Invalid data: title is required and must be a non-empty string" };
    // }

    // if (!data.filters || typeof data.filters !== 'object') {
    //   return { success: false, message: "Invalid data: filters is required and must be an object" };
    // }

    // if (!filterOptions || typeof filterOptions !== 'object') {
    //   return { success: false, message: "Invalid filterOptions: filterOptions is required and must be an object" };
    // }

    // const url = `${process.env.NEXT_PUBLIC_API_URL}/products/save-search/store`;
    const url = `${process.env.NEXT_PUBLIC_API_URL}/user-search/store`;
    const response = await axios.post(url, data, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });

    const result = response.data;

    return {
      success: true,
      message: "Search saved successfully",
      data: result,
    };
  } catch (error: any) {
    return {
      success: false,
      message:
        error.response?.data?.message ||
        error.message ||
        "Failed to save search",
    };
  }
}

export async function indexSearches(token: string): Promise<any> {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/user-search`;

    const headers: Record<string, string> = {
      "Accept-Language": locale,
      "Content-Type": "application/json",
      Authorization: "Bearer " + token,
    };

    const res = await axios.get(url, { headers });
    const result = res?.data?.data?.userSearch;

    return {
      success: true,
      message: "User search Fetch Successfully!",
      data: result,
    };
  } catch (error: any) {
    throw error;
  }
}

export async function deleteSearch(
  token: string,
  { searchId }: { searchId: string }
): Promise<any> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/user-search/${searchId}/delete`;
    const response = await axios.delete(url, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });

    const result = response.data;

    return {
      success: true,
      message: "Search Deleted successfully",
      data: result,
    };
  } catch (error: any) {
    return {
      success: false,
      message:
        error.response?.data?.message ||
        error.message ||
        "Failed to save search",
    };
  }
}

export async function updateSearch(
  token: string,
  { saveSearchId, data }: { saveSearchId: string; data: any }
): Promise<any> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/user-search/${saveSearchId}/update`;
    const response = await axios.post(url, data, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
    });

    const result = response.data;

    return {
      success: true,
      message: "Search Updated successfully",
      data: result,
    };
  } catch (error: any) {
    console.error("Save search error:", error);
    return {
      success: false,
      message:
        error.response?.data?.message ||
        error.message ||
        "Failed to save search",
    };
  }
}
