const API_BASE_URL = 'https://karibeo.lesoluciones.net:8443/api';

export interface Review {
  id: string;
  itemId: string;
  userId: string;
  userName: string;
  userAvatar: string;
  rating: number;
  comment: string;
  images: string[];
  createdAt: string;
  helpful: number;
  isHelpful: boolean;
  replies: ReviewReply[];
  canReply: boolean;
}

export interface ReviewReply {
  id: string;
  authorId: string;
  authorName: string;
  authorAvatar: string;
  content: string;
  createdAt: string;
  images?: string[];
}

export interface ReviewStats {
  average: number;
  totalRatings: number;
  totalReviews: number;
  breakdown: {
    [key: number]: {
      count: number;
      percentage: number;
    };
  };
}

class ReviewService {
  private async getAuthToken(): Promise<string | null> {
    // Get token from localStorage or your preferred auth method
    return localStorage.getItem('auth_token');
  }

  async getReviews(itemId?: string): Promise<Review[]> {
    const token = await this.getAuthToken();
    const url = itemId 
      ? `${API_BASE_URL}/reviews?item_id=${itemId}`
      : `${API_BASE_URL}/reviews`;

    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to fetch reviews');
    }

    const data = await response.json();
    return data.map((review: any) => ({
      id: review.id,
      itemId: review.item_id,
      userId: review.user_id,
      userName: review.user_name || 'Anonymous',
      userAvatar: review.user_avatar || '',
      rating: review.rating,
      comment: review.comment,
      images: review.images || [],
      createdAt: new Date(review.created_at).toLocaleString(),
      helpful: review.helpful_count || 0,
      isHelpful: review.is_helpful || false,
      replies: review.replies || [],
      canReply: true,
    }));
  }

  async createReview(data: {
    itemId: string;
    rating: number;
    comment: string;
    images?: string[];
  }): Promise<Review> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/reviews`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        item_id: data.itemId,
        rating: data.rating,
        comment: data.comment,
        images: data.images || [],
      }),
    });

    if (!response.ok) {
      throw new Error('Failed to create review');
    }

    return await response.json();
  }

  async createReply(reviewId: string, content: string, images?: string[]): Promise<ReviewReply> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/reviews/${reviewId}/replies`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        content,
        images: images || [],
      }),
    });

    if (!response.ok) {
      throw new Error('Failed to create reply');
    }

    return await response.json();
  }

  async markAsHelpful(reviewId: string): Promise<void> {
    const token = await this.getAuthToken();

    const response = await fetch(`${API_BASE_URL}/reviews/${reviewId}/helpful`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to mark review as helpful');
    }
  }

  async getReviewStats(itemId?: string): Promise<ReviewStats> {
    const token = await this.getAuthToken();
    const url = itemId 
      ? `${API_BASE_URL}/reviews/stats?item_id=${itemId}`
      : `${API_BASE_URL}/reviews/stats`;

    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error('Failed to fetch review stats');
    }

    return await response.json();
  }
}

export const reviewService = new ReviewService();
