// lib/api.ts - API service for Next.js
export interface Event {
  id: number;
  code: string;
  year: string;
  subject: string;
  title: string;
  subTitle?: string;
  description: string;
  detail: string;
  date: string;
  mainImage?: string;
  galleryImages?: string[];
  venue?: Venue[];
  highlights?: string[];
  organisers?: string[];
  fee?: Fee[];  // Updated to match backend structure
  phone: string;
  email: string;
  isActive: boolean;
  professors?: Professor[];
}

interface Venue {
  title: string;
  date: string;
  address: string;
  info: string;
}

interface Fee {
  description: string;  // Updated from 'desc' to 'description'
  cost: number;
}

interface Professor {
  id: number;
  name: string;
}

class EventAPI {
  private baseUrl: string;

  constructor() {
    // Use environment variable for API URL
    this.baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080';
  }

  // File upload method
  async uploadImage(file: File): Promise<{url: string, filename: string}> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch(`${this.baseUrl}/api/files/upload`, {
        method: 'POST',
        body: formData, // Don't set Content-Type header for FormData
      });

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

      return await response.json();
    } catch (error) {
      console.error('Error uploading image:', error);
      throw error;
    }
  }

  // Upload multiple images
  async uploadMultipleImages(files: File[]): Promise<{url: string, filename: string}[]> {
    try {
      const uploadPromises = files.map(file => this.uploadImage(file));
      return await Promise.all(uploadPromises);
    } catch (error) {
      console.error('Error uploading multiple images:', error);
      throw error;
    }
  }

  async getAllEvents(): Promise<Event[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/events`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

      return await response.json();
    } catch (error) {
      console.error('Error fetching events:', error);
      throw error;
    }
  }

  async getEventById(id: number): Promise<Event> {
    try {
      const response = await fetch(`${this.baseUrl}/api/events/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

      return await response.json();
    } catch (error) {
      console.error('Error fetching event:', error);
      throw error;
    }
  }

  async getUpcomingEvents(): Promise<Event[]> {
    try {
      const events = await this.getAllEvents();
      const currentDate = new Date();
      
      return events
        .filter(event => {
          if (!event.isActive) return false;
          
          // Parse the date string (assuming format like "28 September 2025")
          const eventDate = new Date(event.date);
          return eventDate >= currentDate;
        })
        .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
    } catch (error) {
      console.error('Error fetching upcoming events:', error);
      throw error;
    }
  }

  async getPastEvents(): Promise<Event[]> {
    try {
      const events = await this.getAllEvents();
      const currentDate = new Date();
      
      return events
        .filter(event => {
          if (!event.isActive) return false;
          
          const eventDate = new Date(event.date);
          return eventDate < currentDate;
        })
        .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
    } catch (error) {
      console.error('Error fetching past events:', error);
      throw error;
    }
  }
}

export const eventAPI = new EventAPI();