// "use server";
import axios from "axios";
import { JOB_FORM_TYPE } from "../formTypes";
import { getStoredLocale } from "../getLocale";

interface JobsResponse {
  success: boolean;
  message?: string;
  data?: {
    jobs: any[];
    pagination: {
      page: number;
      limit: number;
    };
  };
}

export async function fetchJobsAction(
  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/${JOB_FORM_TYPE}${queryString}`;

    const response = await axios.get(url, {
      headers: {
        "Accept-Language": locale,
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    if (response.data.data) {
      const data = response.data.data.jobs;
      const processedJobs = transformJob(data);

      // if (response.data?.status === true) {
      //   const rawJobs = response.data.data?.jobs || [];

      //   if (!Array.isArray(rawJobs)) {
      //     return { success: false, message: "Invalid jobs 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 getHiringStatus = (slug: string) => {
      //       const attr = attributes.find((attr: any) => attr.attributeSlug === slug);
      //       if (!attr) return '';

      //       // For radio fields, attr.value usually stores the selected option's ID
      //       if (attr.type === 'radio' && attr.value) {
      //         const selectedOption = attr.attributeOptions?.find(
      //           (opt: any) => opt._id === attr.value
      //         );
      //         return selectedOption?.value || '';
      //       }

      //       // If it's an object (rare case)
      //       if (typeof attr.value === 'object' && attr.value.value) {
      //         return attr.value.value;
      //       }

      //       // If it's just a plain string value
      //       return String(attr.value || '');
      //     };

      //     const employmentType = getEmploymentType('employment-type');
      //     const hiringStatus = getHiringStatus('hiring-or-job-hunting');

      //     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,
      //       hiringStatus,
      //       createdAt,
      //       creator
      //     };
      //   });

      return {
        success: true,
        data: {
          jobs: processedJobs,
          // pagination: response.data.data?.pagination || {}
          pagination: response.data.data?.pagination || {},
        },
        message: response.data.message || "Jobs fetched successfully",
      };
    } else {
      return { success: false, message: "Failed to fetch jobs" };
    }
  } catch (error: any) {
    return {
      success: false,
      message: error?.response?.data?.message || "Failed to fetch jobs",
    };
  }
}

export async function getJob(
  { jobId }: { jobId: string }
): Promise<any> {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/home/job/${jobId}/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: "Job Fetch Successfully!",
      data: result,
    };
  } catch (error: any) {
    throw error;
  }
}

const transformJob = (data: any) => {
  if (!Array.isArray(data) || data?.length === 0) return []; // Return empty array if no data

  const jobData = data.map((item: any) => {
    const obj: any = {
      id: item?._id || null,
      createdAt: item?.createdAt || null,
      title: null,
      description: null,
      employmentType: null,
      cityOrState: null,
      salary: null,
      hiringOrJobHunting: null,
    };

    if (Array.isArray(item?.attributes)) {
      item?.attributes.forEach((attr: any) => {
        const slug = attr?.attributeSlug;

        if (!slug) return; // Skip if slug is undefined

        switch (slug) {
          case "title":
            obj.title = attr?.value ?? null;
            break;
          case "description":
          case "short-description":
            obj.description = attr?.value ?? null;
            break;
          case "employment-type":
            const employmentId = attr?.value;
            const employmentOption = attr?.attributeOptions?.find(
              (opt: any) => opt?._id === employmentId
            );
            obj.employmentType = employmentOption?.value ?? null;
            break;
          case "city":
          case "state":
            if (Array.isArray(attr?.value) && attr?.value?.length > 0) {
              obj.cityOrState = attr?.value[0]?.value ?? null;
            } else {
              obj.cityOrState = attr?.value ?? null;
            }
            break;
          case "salary":
            obj.salary = attr?.value ?? null;
            break;
          case "hiring-or-job-hunting":
            const selectedOption = attr?.attributeOptions?.find(
              (opt: any) => opt?._id === attr?.value
            );
            obj.hiringOrJobHunting = selectedOption?.value ?? null;
            break;
          default:
            break;
        }
      });
    }
    return obj;
  });

  return jobData;
};
