import { SiteSettings, GolfServicesPageData, Post, Page, PaginatedResponse, AuthResponse, AboutPageData, GolfAcademyData, BookLessonData, SlotAvailability, GroupServicesData, GolfDevelopmentFundData, EventGalleryItem, EventGallerySettingsData, GolfIdData, MembershipOffersData, UpgradeOffersData, MemberRewardsData, BonusPointsData, HomePageData, PartnersData, ContactPageData, PrivacyPageData, EshopData, EventsPageData, Service, SidebarContentItem, Package } from '@/types';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api';

class ApiClient {
  private baseUrl: string;
  private token: string | null = null;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  setToken(token: string | null) {
    this.token = token;
    if (typeof window !== 'undefined') {
      if (token) {
        localStorage.setItem('token', token);
      } else {
        localStorage.removeItem('token');
      }
    }
  }

  getToken(): string | null {
    if (this.token) return this.token;
    if (typeof window !== 'undefined') {
      return localStorage.getItem('token');
    }
    return null;
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<T> {
    const url = `${this.baseUrl}${endpoint}`;
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...options.headers,
    };

    const token = this.getToken();
    if (token) {
      (headers as Record<string, string>)['Authorization'] = `Bearer ${token}`;
    }

    const response = await fetch(url, {
      ...options,
      headers,
    });

    if (!response.ok) {
      const error = await response.json().catch(() => ({ error: 'An error occurred' }));
      throw new Error(error.error || 'An error occurred');
    }

    return response.json();
  }

  // Settings
  async getSettings(): Promise<SiteSettings> {
    return this.request<SiteSettings>('/settings');
  }

  async getHomepageData(): Promise<Partial<SiteSettings>> {
    return this.request<Partial<SiteSettings>>('/settings/homepage');
  }

  // Golf Services Page
  async getGolfServicesPage(): Promise<GolfServicesPageData> {
    return this.request<GolfServicesPageData>('/golf-services-page');
  }

  async getServices(): Promise<Service[]> {
    return this.request<Service[]>('/services');
  }

  async getService(slug: string): Promise<Service> {
    return this.request<Service>(`/services/${slug}`);
  }

  // Posts
  async getPosts(params?: {
    category?: string;
    tag?: string;
    page?: number;
    limit?: number;
  }): Promise<PaginatedResponse<Post>> {
    const searchParams = new URLSearchParams();
    if (params?.category) searchParams.set('category', params.category);
    if (params?.tag) searchParams.set('tag', params.tag);
    if (params?.page) searchParams.set('page', params.page.toString());
    if (params?.limit) searchParams.set('limit', params.limit.toString());

    const query = searchParams.toString();
    return this.request<PaginatedResponse<Post>>(`/posts${query ? `?${query}` : ''}`);
  }

  async getFeaturedPosts(): Promise<Post[]> {
    return this.request<Post[]>('/posts/featured');
  }

  async getPost(slug: string): Promise<Post> {
    return this.request<Post>(`/posts/${slug}`);
  }

  async getCategories(): Promise<string[]> {
    return this.request<string[]>('/posts/categories');
  }

  // Pages
  async getPages(): Promise<Page[]> {
    return this.request<Page[]>('/pages');
  }

  async getPage(slug: string): Promise<Page> {
    return this.request<Page>(`/pages/${slug}`);
  }

  // About
  async getAboutPage(): Promise<AboutPageData> {
    return this.request<AboutPageData>('/about');
  }

  // Golf Academy
  async getGolfAcademy(): Promise<GolfAcademyData> {
    return this.request<GolfAcademyData>('/golf-academy');
  }

  async submitCoachInquiry(data: { firstName: string; lastName: string; email: string; message?: string }): Promise<{ message: string }> {
    return this.request<{ message: string }>('/golf-academy/inquiries', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // Book Lessons
  async getBookLesson(): Promise<BookLessonData> {
    return this.request<BookLessonData>('/book-lessons');
  }

  async getBookLessonAvailability(date: string): Promise<{ date: string; slots: SlotAvailability[] }> {
    return this.request<{ date: string; slots: SlotAvailability[] }>(`/book-lessons/availability?date=${date}`);
  }

  async submitLessonBooking(data: {
    date: string;
    timeSlot: string;
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    golfId?: string;
  }): Promise<{ message: string }> {
    return this.request<{ message: string }>('/book-lessons/bookings', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // Group Services
  async getGroupServices(): Promise<GroupServicesData> {
    return this.request<GroupServicesData>('/group-services');
  }

  async getEventsPage(): Promise<EventsPageData> {
    return this.request<EventsPageData>('/events-page');
  }

  // Golf Development Fund
  async getGDF(): Promise<GolfDevelopmentFundData> {
    return this.request<GolfDevelopmentFundData>('/gdf');
  }

  // Event Gallery
  async getEventGallery(): Promise<EventGalleryItem[]> {
    return this.request<EventGalleryItem[]>('/event-gallery');
  }

  async getEventGallerySettings(): Promise<EventGallerySettingsData> {
    return this.request<EventGallerySettingsData>('/event-gallery/settings');
  }

  async getEventGalleryBySlug(slug: string): Promise<EventGalleryItem> {
    return this.request<EventGalleryItem>(`/event-gallery/${slug}`);
  }

  // Golf ID
  async getGolfId(): Promise<GolfIdData> {
    return this.request<GolfIdData>('/golf-id');
  }

  // Membership Offers
  async getMembershipOffers(): Promise<MembershipOffersData> {
    return this.request<MembershipOffersData>('/membership-offers');
  }

  // Upgrade Offers
  async getUpgradeOffers(): Promise<UpgradeOffersData> {
    return this.request<UpgradeOffersData>('/upgrade-offers');
  }

  // Member Rewards
  async getMemberRewards(): Promise<MemberRewardsData> {
    return this.request<MemberRewardsData>('/member-rewards');
  }

  // Bonus Points
  async getBonusPoints(): Promise<BonusPointsData> {
    return this.request<BonusPointsData>('/bonus-points');
  }

  // Partners
  async getPartners(): Promise<PartnersData> {
    return this.request<PartnersData>('/partners');
  }

  // Eshop
  async getEshop(): Promise<EshopData> {
    return this.request<EshopData>('/eshop');
  }

  // Contact Page
  async getContactPage(): Promise<ContactPageData> {
    return this.request<ContactPageData>('/contact');
  }

  async submitContactInquiry(data: { name: string; phone?: string; email: string; message: string }): Promise<{ _id: string }> {
    return this.request<{ _id: string }>('/contact/inquiries', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  // Privacy Page
  async getPrivacyPage(): Promise<PrivacyPageData> {
    return this.request<PrivacyPageData>('/privacy');
  }

  // Sidebar Content
  async getSidebarContent(): Promise<SidebarContentItem[]> {
    return this.request<SidebarContentItem[]>('/sidebar-content');
  }

  // Homepage
  async getHomePageContent(): Promise<HomePageData> {
    return this.request<HomePageData>('/homepage');
  }

  // Auth
  async login(email: string, password: string): Promise<AuthResponse> {
    const response = await this.request<AuthResponse>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ email, password }),
    });
    this.setToken(response.token);
    return response;
  }

  // Packages
  async getPackages(): Promise<Package[]> {
    return this.request<Package[]>('/packages');
  }

  async logout() {
    this.setToken(null);
  }

  async getCurrentUser() {
    return this.request<{ user: AuthResponse['user'] }>('/auth/me');
  }
}

export const api = new ApiClient(API_URL);
export default api;
