import axios from 'axios';
import type { AxiosInstance } from 'axios';
import type { ApiResponse } from '../types';

class ApiService {
  private api: AxiosInstance;
  private baseURL: string = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api';

  constructor() {
    this.api = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // Request interceptor to add auth token
    this.api.interceptors.request.use(
      (config) => {
        // For Telegram Web App, use X-Telegram-WebApp-Init-Data header
        const telegramInitData = localStorage.getItem('telegram_init_data');
        if (telegramInitData) {
          config.headers['X-Telegram-WebApp-Init-Data'] = telegramInitData;
        } else {
          // Fallback to Bearer token for non-Telegram auth
          const token = localStorage.getItem('auth_token');
          if (token) {
            config.headers.Authorization = `Bearer ${token}`;
          }
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // Response interceptor to handle errors
    this.api.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          localStorage.removeItem('auth_token');
          window.location.href = '/';
        }
        return Promise.reject(error);
      }
    );
  }

  // Auth methods
  async validateTelegramInitData(initData: string): Promise<ApiResponse<any>> {
    const response = await this.api.post('/auth/validate', { initData });
    return response.data;
  }

  async getCurrentUser(): Promise<ApiResponse<any>> {
    const response = await this.api.get('/auth/me');
    return response.data;
  }

  // Quiz methods
  async getAllQuizzes(): Promise<ApiResponse<any[]>> {
    const response = await this.api.get('/quizzes');
    return response.data;
  }

  async getQuizById(id: number): Promise<ApiResponse<any>> {
    const response = await this.api.get(`/quizzes/${id}`);
    return response.data;
  }

  async submitQuiz(id: number, submissionData: any): Promise<ApiResponse<any>> {
    const response = await this.api.post(`/quizzes/${id}/submit`, submissionData);
    return response.data;
  }

  async canRepeatQuiz(id: number): Promise<ApiResponse<any>> {
    const response = await this.api.get(`/quizzes/${id}/can-repeat`);
    return response.data;
  }

  // Reward methods
  async getAllRewards(): Promise<ApiResponse<any[]>> {
    const response = await this.api.get('/rewards');
    return response.data;
  }

  async purchaseReward(id: number): Promise<ApiResponse<any>> {
    const response = await this.api.post(`/rewards/${id}/purchase`);
    return response.data;
  }

  // User methods
  async getUserProfile(): Promise<ApiResponse<any>> {
    const response = await this.api.get('/me');
    return response.data;
  }

  async getUserTransactions(): Promise<ApiResponse<any[]>> {
    const response = await this.api.get('/user/transactions');
    return response.data;
  }

  async getUserPurchases(): Promise<ApiResponse<any[]>> {
    const response = await this.api.get('/user/purchases');
    return response.data;
  }

  // QR methods
  async validateQR(payload: string): Promise<ApiResponse<any>> {
    const response = await this.api.post('/qr/validate', { payload });
    return response.data;
  }

  // Admin methods
  async createQuiz(quiz: any): Promise<ApiResponse<any>> {
    const response = await this.api.post('/admin/quizzes', quiz);
    return response.data;
  }

  async updateQuiz(id: number, quiz: any): Promise<ApiResponse<any>> {
    const response = await this.api.put(`/admin/quizzes/${id}`, quiz);
    return response.data;
  }

  async deleteQuiz(id: number): Promise<ApiResponse<any>> {
    const response = await this.api.delete(`/admin/quizzes/${id}`);
    return response.data;
  }

  async createQuestion(quizId: number, question: any): Promise<ApiResponse<any>> {
    const response = await this.api.post(`/admin/quizzes/${quizId}/questions`, question);
    return response.data;
  }

  async updateQuestion(quizId: number, questionId: number, question: any): Promise<ApiResponse<any>> {
    const response = await this.api.put(`/admin/quizzes/${quizId}/questions/${questionId}`, question);
    return response.data;
  }

  async deleteQuestion(quizId: number, questionId: number): Promise<ApiResponse<any>> {
    const response = await this.api.delete(`/admin/quizzes/${quizId}/questions/${questionId}`);
    return response.data;
  }

  async createReward(reward: any): Promise<ApiResponse<any>> {
    const response = await this.api.post('/admin/rewards', reward);
    return response.data;
  }

  async updateReward(id: number, reward: any): Promise<ApiResponse<any>> {
    const response = await this.api.put(`/admin/rewards/${id}`, reward);
    return response.data;
  }

  async deleteReward(id: number): Promise<ApiResponse<any>> {
    const response = await this.api.delete(`/admin/rewards/${id}`);
    return response.data;
  }

  async grantStars(data: any): Promise<ApiResponse<any>> {
    const response = await this.api.post('/admin/users/grant-stars', data);
    return response.data;
  }

  async createOperator(data: any): Promise<ApiResponse<any>> {
    const response = await this.api.post('/admin/operators', data);
    return response.data;
  }

  async deleteOperator(id: number): Promise<ApiResponse<any>> {
    const response = await this.api.delete(`/admin/operators/${id}`);
    return response.data;
  }

  async getAnalytics(): Promise<ApiResponse<any>> {
    const response = await this.api.get('/admin/analytics');
    return response.data;
  }

  async generateQRCodes(data: any): Promise<ApiResponse<any>> {
    const response = await this.api.post('/admin/qrcodes', data);
    return response.data;
  }

  // Utility method to set auth token
  setAuthToken(token: string) {
    localStorage.setItem('auth_token', token);
  }

  // Utility method to set Telegram init data
  setTelegramInitData(initData: string) {
    localStorage.setItem('telegram_init_data', initData);
  }

  // Utility method to clear auth token
  clearAuthToken() {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('telegram_init_data');
  }

  // Utility method to check if user is authenticated
  isAuthenticated(): boolean {
    return !!(localStorage.getItem('auth_token') || localStorage.getItem('telegram_init_data'));
  }

  // Check if user has admin privileges
  async checkAdminRole(): Promise<ApiResponse<{ role: string }>> {
    const response = await this.api.get('/auth/admin-role');
    return response.data;
  }
}

export const apiService = new ApiService();
export default apiService;