// "use server";
import axios from "axios";
import { COMMUNITY_EVENT_FORM_TYPE } from "../formTypes";
import { getStoredLocale } from "../getLocale";

interface CommunitiesResponse {
  success: boolean;
  message?: string;
  data?: {
    communities: any[];
    pagination: {
      page: number;
      limit: number;
    };
  };
}


export async function fetchCommunitiesAction(params?: {
  search?: string;
  limit?: number;
  page?: number;
}, locale: string = 'en'): Promise<CommunitiesResponse> {
  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/${COMMUNITY_EVENT_FORM_TYPE}${queryString}`;

    const response = await axios.get(url, {
      headers: {
        "Accept-Language": locale,
        "Content-Type": "application/json",
        Accept: "application/json",
      }
    });
    if (response.data?.status === true) {
      const rawCommunities = response.data.data?.communities || [];

      if (!Array.isArray(rawCommunities)) {
        return { success: false, message: "Invalid communities data format" };
      }

      const processedCommunities = rawCommunities.map(community => {
        const { attributes, createdAt, creator, _id } = community;


        const getValue = (slug: string) => {
          const attr = attributes.find((attr: any) => attr.attributeSlug === slug);
          return attr?.value || '';
        };


        // const parseLocationValue = (value: any) => {
        //   // Handle both object and string formats from your API
        //   if (typeof value === 'object' && value !== null) {
        //     return value.value || '';
        //   }
        //   if (typeof value === 'string') {
        //     try {
        //       const parsed = JSON.parse(value);
        //       return parsed.value || value;
        //     } catch {
        //       return value;
        //     }
        //   }
        //   return value || '';
        // };
        const parseLocationValue = (value: any) => {
          if (!value) return '';

          // If it's an array (like [ { key, value } ])
          if (Array.isArray(value)) {
            return value[0]?.value || '';
          }

          // If it's an object
          if (typeof value === 'object' && value !== null) {
            return value.value || '';
          }

          // If it's a JSON string
          if (typeof value === 'string') {
            try {
              const parsed = JSON.parse(value);
              if (Array.isArray(parsed)) {
                return parsed[0]?.value || '';
              }
              if (typeof parsed === 'object') {
                return parsed.value || value;
              }
              return parsed;
            } catch {
              return value;
            }
          }

          return '';
        };

        const getImage = () => {
          // Look for single image uploader first
          const singleImageAttr = attributes.find((attr: any) =>
            attr.attributeSlug === 'upload-single-image' &&
            attr.meta?.files?.[0]?.location
          );

          if (singleImageAttr?.meta?.files?.[0]?.location) {
            return singleImageAttr.meta.files[0].location;
          }

          // Fallback to multiple images
          const multiImageAttr = attributes.find((attr: any) =>
            attr.attributeSlug === 'upload-multiple-images' &&
            attr.meta?.files?.[0]?.location
          );

          if (multiImageAttr?.meta?.files?.[0]?.location) {
            return multiImageAttr.meta.files[0].location;
          }

          return '/event.webp';
        };


        const formatEventDateTime = (dateValue: any, timeValue: any) => {
          let date = '';
          let time = '';

          if (dateValue) {
            try {
              // Handle both string and object formats
              const dateStr = typeof dateValue === 'string' ? dateValue : JSON.stringify(dateValue);
              const cleanDateStr = dateStr.replace(/"/g, ''); // Remove quotes
              const dateObj = new Date(cleanDateStr);
              date = dateObj.toLocaleDateString('en-US', {
                day: 'numeric',
                month: 'short',
                year: 'numeric'
              });
            } catch {
              date = '';
            }
          }

          if (timeValue) {
            try {
              // Handle both string and object formats
              const timeStr = typeof timeValue === 'string' ? timeValue : JSON.stringify(timeValue);
              const cleanTimeStr = timeStr.replace(/"/g, ''); // Remove quotes
              const timeObj = new Date(cleanTimeStr);
              time = timeObj.toLocaleTimeString('en-US', {
                hour: 'numeric',
                minute: '2-digit',
                hour12: true
              });
            } catch {
              time = '';
            }
          }

          return { date, time };
        };


        const country = parseLocationValue(getValue('country'));
        const state = parseLocationValue(getValue('state'));
        const city = parseLocationValue(getValue('city'));


        const locationParts = [city, state, country].filter(Boolean);
        const location = locationParts.length > 0 ? locationParts.join(', ') : null;


        const { date, time } = formatEventDateTime(getValue('date'), getValue('time'));


        const isEvent = attributes.some((attr: any) => attr.attributeSlug === 'title');
        const type = isEvent ? 'event' : 'community';


        const title = getValue('title') || 'Untitled';
        const description = getValue('description') || getValue('short-description') || '';

        return {
          _id,
          title,
          description,
          date,
          time,
          location,
          image: getImage(),
          type,
          createdAt,
          creator
        };
      });

      return {
        success: true,
        data: {
          communities: processedCommunities,
          pagination: response.data.data?.pagination || {}
        },
        message: response.data.message || "Communities fetched successfully"
      };
    } else {
      return { success: false, message: "Failed to fetch communities" };
    }
  } catch (error: any) {
    return {
      success: false,
      message: error?.response?.data?.message || "Failed to fetch communities"
    };
  }
}

export async function getCommunity({
  communityId
}: { communityId: string }): Promise<any> {
  try {
    const locale = getStoredLocale();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/home/community-event/${communityId}/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: "Community Fetch Successfully!",
      data: result,
    };
  } catch (error: any) {
    throw error;
  }
}
