import axios, { type AxiosInstance, AxiosError } from 'axios';
import type { 
  User, Hook, WhatsAppAccount, EventLog, APIKey,
  LoginRequest, LoginResponse
} from '../types';

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080';

class ApiClient {
  private client: AxiosInstance;

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

    // Request interceptor to add auth token
    this.client.interceptors.request.use((config) => {
      const token = this.getToken();
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

    // Response interceptor for error handling
    this.client.interceptors.response.use(
      (response) => response,
      (error: AxiosError) => {
        if (error.response?.status === 401) {
          // Token expired or invalid, clear auth and redirect
          this.clearAuth();
          window.location.href = '/ui/login';
        }
        return Promise.reject(error);
      }
    );
  }

  // Token management
  private getToken(): string | null {
    return localStorage.getItem('auth_token');
  }

  private setToken(token: string): void {
    localStorage.setItem('auth_token', token);
  }

  private clearAuth(): void {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user');
  }

  // Auth endpoints
  async login(credentials: LoginRequest): Promise<LoginResponse> {
    const { data } = await this.client.post<LoginResponse>('/api/v1/auth/login', credentials);
    if (data.token) {
      this.setToken(data.token);
      localStorage.setItem('user', JSON.stringify(data.user));
    }
    return data;
  }

  async logout(): Promise<void> {
    try {
      await this.client.post('/api/v1/auth/logout');
    } finally {
      this.clearAuth();
    }
  }

  getCurrentUser(): User | null {
    const userStr = localStorage.getItem('user');
    return userStr ? JSON.parse(userStr) : null;
  }

  isAuthenticated(): boolean {
    return !!this.getToken();
  }

  // Unified query endpoint
  async query(request: {
    action: 'list' | 'get' | 'create' | 'update' | 'delete';
    table: string;
    id?: string;
    data?: Record<string, any>;
    filters?: Record<string, any>;
    limit?: number;
    offset?: number;
  }): Promise<any> {
    const { data } = await this.client.post('/api/v1/query', request);
    return data;
  }

  // Users API
  async getUsers(): Promise<User[]> {
    const { data } = await this.client.get<User[]>('/api/v1/users');
    return data;
  }

  async getUser(id: string): Promise<User> {
    const { data } = await this.client.get<User>(`/api/v1/users/${id}`);
    return data;
  }

  async createUser(user: Partial<User>): Promise<User> {
    const { data } = await this.client.post<User>('/api/v1/users', user);
    return data;
  }

  async updateUser(id: string, user: Partial<User>): Promise<User> {
    const { data } = await this.client.put<User>(`/api/v1/users/${id}`, user);
    return data;
  }

  async deleteUser(id: string): Promise<void> {
    await this.client.delete(`/api/v1/users/${id}`);
  }

  // Hooks API
  async getHooks(): Promise<Hook[]> {
    const { data } = await this.client.get<Hook[]>('/api/v1/hooks');
    return data;
  }

  async getHook(id: string): Promise<Hook> {
    const { data } = await this.client.get<Hook>(`/api/v1/hooks/${id}`);
    return data;
  }

  async createHook(hook: Partial<Hook>): Promise<Hook> {
    const { data } = await this.client.post<Hook>('/api/v1/hooks', hook);
    return data;
  }

  async updateHook(id: string, hook: Partial<Hook>): Promise<Hook> {
    const { data } = await this.client.put<Hook>(`/api/v1/hooks/${id}`, hook);
    return data;
  }

  async deleteHook(id: string): Promise<void> {
    await this.client.delete(`/api/v1/hooks/${id}`);
  }

  // WhatsApp Accounts API
  async getAccounts(): Promise<WhatsAppAccount[]> {
    const { data } = await this.client.get<WhatsAppAccount[]>('/api/v1/whatsapp_accounts');
    return data;
  }

  async getAccount(id: string): Promise<WhatsAppAccount> {
    const { data } = await this.client.get<WhatsAppAccount>(`/api/v1/whatsapp_accounts/${id}`);
    return data;
  }

  async createAccount(account: Partial<WhatsAppAccount>): Promise<WhatsAppAccount> {
    const { data} = await this.client.post<WhatsAppAccount>('/api/v1/whatsapp_accounts', account);
    return data;
  }

  async updateAccount(id: string, account: Partial<WhatsAppAccount>): Promise<WhatsAppAccount> {
    const { data } = await this.client.put<WhatsAppAccount>(`/api/v1/whatsapp_accounts/${id}`, account);
    return data;
  }

  async deleteAccount(id: string): Promise<void> {
    await this.client.delete(`/api/v1/whatsapp_accounts/${id}`);
  }

  // Event Logs API
  async getEventLogs(params?: { limit?: number; offset?: number }): Promise<EventLog[]> {
    const { data } = await this.client.get<EventLog[]>('/api/v1/event_logs', { params });
    return data;
  }

  // API Keys API
  async getAPIKeys(): Promise<APIKey[]> {
    const { data } = await this.client.get<APIKey[]>('/api/v1/api_keys');
    return data;
  }

  async createAPIKey(apiKey: Partial<APIKey>): Promise<APIKey> {
    const { data } = await this.client.post<APIKey>('/api/v1/api_keys', apiKey);
    return data;
  }

  async deleteAPIKey(id: string): Promise<void> {
    await this.client.delete(`/api/v1/api_keys/${id}`);
  }

  // Health check
  async healthCheck(): Promise<{ status: string }> {
    const { data } = await this.client.get<{ status: string }>('/health');
    return data;
  }
}

export const apiClient = new ApiClient();
export default apiClient;
