// 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[];
  phone: string;
  email: string;
  isActive: boolean;
  bookSeatLink?: string;  // NEW FIELD
  professors?: Professor[];
}

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

interface Fee {
  description: string;
  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';
  }

  // Helper method to convert relative URLs to absolute URLs
  private getFullImageUrl(imageUrl: string | undefined): string {
    if (!imageUrl || imageUrl.trim() === '') return '';
    
    // If it's already a full URL, return as-is
    if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
      return imageUrl;
    }
    
    // If it's a relative URL, prepend the backend API URL
    const cleanUrl = imageUrl.startsWith('/') ? imageUrl.substring(1) : imageUrl;
    return `${this.baseUrl}/${cleanUrl}`;
  }

  // Process event to fix image URLs
  private processEvent(event: Event): Event {
    return {
      ...event,
      mainImage: this.getFullImageUrl(event.mainImage),
      galleryImages: event.galleryImages?.map(img => this.getFullImageUrl(img)).filter(img => img !== '') || []
    };
  }

  // 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,
      });

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

      const result = await response.json();
      
      // Ensure the URL is absolute
      if (result.url) {
        result.url = this.getFullImageUrl(result.url);
      }
      
      return result;
    } 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',
        },
        cache: 'no-store', // Ensure fresh data
      });

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

      const events = await response.json();
      // Process all events to fix image URLs
      return events.map((event: Event) => this.processEvent(event));
    } 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',
        },
        cache: 'no-store',
      });

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

      const event = await response.json();
      // Process event to fix image URLs
      return this.processEvent(event);
    } 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();