import { getWebhookUrl } from '@/lib/config';

export interface Event {
  id?: string | number;
  user_id?: number;
  name?: string;
  description?: string;
  location?: string;
  url?: string;
  image?: string;
  manager_name?: string;
  manager_email?: string;
  guests?: any;
  begin_date?: string; // ISO date string (YYYY-MM-DD)
  end_date?: string;   // ISO date string (YYYY-MM-DD)
  creation_date?: number;
  last_update?: number;
}

interface EventData {
  name: string;
  description?: string;
  location?: string;
  url?: string;
  image?: string;
  manager_name?: string;
  manager_email?: string;
  begin_date?: string; // YYYY-MM-DD
  end_date?: string;   // YYYY-MM-DD
}

export const createEventManually = async (eventData: EventData): Promise<any> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/event/new_manual`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        ...eventData,
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('Error creating event manually:', error);
    throw error;
  }
};

export const fetchCurrentEvents = async (apiFetch: Function): Promise<Event[]> => {
  const webhookUrl = `${getWebhookUrl()}/events/get_current`;
  
  try {
    const response = await apiFetch(webhookUrl, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });
    
    if (!response.ok) throw new Error('Failed to fetch events');
    
    const data = await response.json();
    return Array.isArray(data) ? data : data ? [data] : [];
  } catch (error) {
    console.error('Error fetching events:', error);
    throw error;
  }
}

export const fetchEvents = async (apiFetch: Function): Promise<Event[]> => {
  const webhookUrl = `${getWebhookUrl()}/events`;
  
  try {
    const response = await apiFetch(webhookUrl, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });
    
    if (!response.ok) throw new Error('Failed to fetch events');
    
    const data = await response.json();
    return Array.isArray(data) ? data : data ? [data] : [];
  } catch (error) {
    console.error('Error fetching events:', error);
    throw error;
  }
}

export const createEventFromUrl = async (url: string): Promise<any> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/event/new_fromurl`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        url,
        command: 'eventmodus_extract_from_url'
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data.message_from_ai || data;
  } catch (error) {
    console.error('Error creating event from URL:', error);
    throw error;
  }
};

// Helper function to format dates to YYYY-MM-DD
export const formatDateForInput = (dateString: string): string => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toISOString().split('T')[0];
};
