import axios from "axios";
import { getStoredLocale } from "../getLocale";
import { SERVICE_FORM_TYPE } from "../formTypes";
import {
  OtherAttribute,
  OtherAttributeMeta,
} from "../../../types/common-types";

interface JobsResponse {
  success: boolean;
  message?: string;
  data?: {
    services: any[];
    pagination: {
      page: number;
      limit: number;
    };
  };
}

export async function fetchServicesAction(
  params?: {
    search?: string;
    limit?: number;
    page?: number;
  },
  locale: string = "en",
): Promise<JobsResponse> {
  try {
    const queryParts = [];
    if (params?.search) queryParts.push(`search=${params.search}`);
    if (params?.limit) queryParts.push(`limit=${params.limit}`);
    if (params?.page) queryParts.push(`page=${params.page}`);

    const queryString = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
    const url = `${process.env.NEXT_PUBLIC_API_URL}/home/services${queryString}`;

    const response = await axios.get(url, {
      headers: {
        "Accept-Language": locale,
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    if (response.data?.status === true) {
      const rawJobs = response.data.data?.services || [];

      if (!Array.isArray(rawJobs)) {
        return { success: false, message: "Invalid services data format" };
      }

      const processedJobs = rawJobs.map((job) => {
        const { attributes, createdAt, creator, _id } = job;

        const getLocationValue = (slug: string) => {
          const attr = attributes.find(
            (attr: any) => attr.attributeSlug === slug,
          );
          if (!attr?.value) return "";

          // Handle object values (like {key, value})
          if (typeof attr.value === "object" && attr.value !== null) {
            return attr.value.value || "";
          }

          // Handle string values that might be JSON
          if (typeof attr.value === "string") {
            try {
              const parsed = JSON.parse(attr.value);
              return parsed.value || attr.value;
            } catch {
              return attr.value;
            }
          }

          return String(attr.value);
        };

        const country = getLocationValue("country");
        const state = getLocationValue("state");
        const city = getLocationValue("city");

        const locationParts = [city, state, country].filter(Boolean);
        const location =
          locationParts.length > 0 ? locationParts.join(", ") : "Location";

        const getEmploymentType = (slug: string) => {
          const attr = attributes.find(
            (attr: any) => attr.attributeSlug === slug,
          );
          if (!attr?.value) return "Full Time";

          // Handle object values (like {key, value})
          if (typeof attr.value === "object" && attr.value !== null) {
            return attr.value.value || "Full Time";
          }

          // Handle string values - try to find in attributeOptions first
          if (typeof attr.value === "string") {
            const selectedOption = attr?.attributeOptions?.find(
              (option: any) => option._id === attr.value,
            );
            if (selectedOption?.value) {
              return selectedOption.value;
            }

            // If not found in options, try parsing as JSON
            try {
              const parsed = JSON.parse(attr.value);
              return parsed.value || attr.value;
            } catch {
              return attr.value;
            }
          }

          return String(attr.value);
        };

        const employmentType = getEmploymentType("employment-type");

        const contactValue =
          attributes.find(
            (attr: any) => attr.attributeSlug === "contact-number",
          )?.value || "";
        let contactNumber = "";

        // Handle object values (like {phone, country_code})
        if (typeof contactValue === "object" && contactValue !== null) {
          const { phone, country_code } = contactValue;
          contactNumber =
            phone && country_code ? `${country_code}${phone}` : phone || "";
        } else if (typeof contactValue === "string") {
          try {
            const parsed = JSON.parse(contactValue);
            const { phone, country_code } = parsed;
            contactNumber =
              phone && country_code ? `${country_code}${phone}` : phone || "";
          } catch {
            contactNumber = contactValue;
          }
        } else {
          contactNumber = String(contactValue);
        }

        const getValue = (slug: string) => {
          const attr = attributes.find(
            (attr: any) => attr.attributeSlug === slug,
          );
          if (!attr?.value) return "";

          // Handle object values (like {key, value})
          if (typeof attr.value === "object" && attr.value !== null) {
            return attr.value.value || "";
          }

          // Handle string values that might be JSON
          if (typeof attr.value === "string") {
            try {
              const parsed = JSON.parse(attr.value);
              return parsed.value || attr.value;
            } catch {
              return attr.value;
            }
          }

          return String(attr.value);
        };

        return {
          _id,
          jobTitle: getValue("title"),
          jobDescription: getValue("description"),
          employmentType: employmentType,
          salary: getValue("salary"),
          location,
          cityOrState: city || "Location",
          contactNumber,
          createdAt,
          creator,
        };
      });

      return {
        success: true,
        data: {
          services: rawJobs,
          pagination: response.data.data?.pagination || {},
        },
        message: response.data.message || "Jobs fetched successfully",
      };
    } else {
      return { success: false, message: "Failed to fetch services" };
    }
  } catch (error: any) {
    return {
      success: false,
      message: error?.response?.data?.message || "Failed to fetch services",
    };
  }
}

export async function getService({
  serviceId,
}: {
  serviceId: string;
}): Promise<any> {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/home/service/${serviceId}/view`;

    const headers: Record<string, string> = {
      "Accept-Language": locale,
      "Content-Type": "application/json",
    };

    const res = await axios.get(url, { headers });
    const result = res?.data?.data;

    return {
      success: true,
      message: "Service Fetch Successfully!",
      data: result,
    };
  } catch (error: any) {
    throw error;
  }
}

export async function getServiceProducts(
  token: string,
  { serviceId }: { serviceId: string },
): Promise<{
  success: boolean;
  message?: string;
  data: {
    productId: string;
    title: string;
    description: string;
    price: number;
    otherAttribute: {
      content:
        | OtherAttribute<"mobile_number">
        | OtherAttribute<"vehicle_number_plate">;
      meta: OtherAttributeMeta;
      valueType: string;
    } | null;
    file_url: string | null;
    createdAt: string;
    isWishlisted: boolean;
    totalNumberOfViews: number;
    distance: number;
    creator: {
      _id: string;
      first_name: string;
      middle_name: null | string;
      last_name: string;
      email: string;
      profile_image: string | null;
    };
  }[];
}> {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/home/service/${serviceId}/product/view`;

    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?.freshProducts;

    return {
      success: true,
      message: "Products Fetch Successfully!",
      data: result,
    };
  } catch (error: any) {
    throw error;
  }
}
