// API Client for frontend to communicate with backend
import { Customer, Order, InventoryItem, Employee, TailoringItem } from '../data';

const API_BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

// API Response interface
interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
  message?: string;
  details?: any;
  total?: number;
  page?: number;
  limit?: number;
  totalPages?: number;
}

// API Client class
export class ApiClient {
  private baseURL: string;
  private token: string | null = null;

  constructor(baseURL: string = API_BASE_URL) {
    this.baseURL = baseURL;
    
    // Get token from localStorage if available
    if (typeof window !== 'undefined') {
      this.token = localStorage.getItem('auth_token');
    }
  }

  // Set authentication token
  setToken(token: string) {
    this.token = token;
    if (typeof window !== 'undefined') {
      localStorage.setItem('auth_token', token);
    }
  }

  // Clear authentication token
  clearToken() {
    this.token = null;
    if (typeof window !== 'undefined') {
      localStorage.removeItem('auth_token');
    }
  }

  // Make HTTP request
  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    const url = `${this.baseURL}/api${endpoint}`;
    
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...((options.headers as Record<string, string>) || {}),
    };

    if (this.token) {
      headers.Authorization = `Bearer ${this.token}`;
    }

    try {
      const response = await fetch(url, {
        ...options,
        headers,
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || `HTTP ${response.status}`);
      }

      return data;
    } catch (error: any) {
      console.error('API Request failed:', error);
      throw error;
    }
  }

  // GET request
  private async get<T>(endpoint: string, params?: Record<string, any>): Promise<ApiResponse<T>> {
    const url = new URL(`${this.baseURL}/api${endpoint}`);
    
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          url.searchParams.append(key, String(value));
        }
      });
    }

    return this.request<T>(url.pathname + url.search);
  }

  // POST request
  private async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined,
    });
  }

  // PUT request
  private async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined,
    });
  }

  // DELETE request
  private async delete<T>(endpoint: string): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'DELETE',
    });
  }

  // ============================================================================
  // AUTHENTICATION
  // ============================================================================

  async login(email: string, password: string): Promise<ApiResponse<{ user: any; token: string }>> {
    const response = await this.post<{ user: any; token: string }>('/auth/login', {
      email,
      password,
    });
    
    if (response.success && response.data?.token) {
      this.setToken(response.data.token);
    }
    
    return response;
  }

  async logout(): Promise<void> {
    this.clearToken();
  }

  // ============================================================================
  // CUSTOMERS
  // ============================================================================

  async getCustomers(params?: {
    page?: number;
    limit?: number;
    search?: string;
    orderBy?: string;
    orderDirection?: 'ASC' | 'DESC';
  }): Promise<ApiResponse<Customer[]>> {
    return this.get<Customer[]>('/customers', params);
  }

  async createCustomer(customer: Omit<Customer, 'id' | 'total_orders' | 'total_spent'>): Promise<ApiResponse<Customer>> {
    return this.post<Customer>('/customers', customer);
  }

  async updateCustomer(id: number, customer: Partial<Customer>): Promise<ApiResponse<Customer>> {
    return this.put<Customer>(`/customers/${id}`, customer);
  }

  async deleteCustomer(id: number): Promise<ApiResponse<void>> {
    return this.delete<void>(`/customers/${id}`);
  }

  async searchCustomers(search: string): Promise<ApiResponse<Customer[]>> {
    return this.get<Customer[]>('/customers', { search });
  }

  // ============================================================================
  // ORDERS
  // ============================================================================

  async getOrders(params?: {
    page?: number;
    limit?: number;
    status?: string;
    customer_id?: number;
    start_date?: string;
    end_date?: string;
    search?: string;
  }): Promise<ApiResponse<Order[]>> {
    return this.get<Order[]>('/orders', params);
  }

  async createOrder(order: any): Promise<ApiResponse<Order>> {
    return this.post<Order>('/orders', order);
  }

  async updateOrder(id: number, order: Partial<Order>): Promise<ApiResponse<Order>> {
    return this.put<Order>(`/orders/${id}`, order);
  }

  async deleteOrder(id: number): Promise<ApiResponse<void>> {
    return this.delete<void>(`/orders/${id}`);
  }

  async updateOrderStatus(id: number, status: string): Promise<ApiResponse<Order>> {
    return this.put<Order>(`/orders/${id}/status`, { status });
  }

  // ============================================================================
  // INVENTORY
  // ============================================================================

  async getInventory(params?: {
    page?: number;
    limit?: number;
    type?: string;
    search?: string;
  }): Promise<ApiResponse<InventoryItem[]>> {
    return this.get<InventoryItem[]>('/inventory', params);
  }

  async createInventoryItem(item: Omit<InventoryItem, 'id'>): Promise<ApiResponse<InventoryItem>> {
    return this.post<InventoryItem>('/inventory', item);
  }

  async updateInventoryItem(id: number, item: Partial<InventoryItem>): Promise<ApiResponse<InventoryItem>> {
    return this.put<InventoryItem>(`/inventory/${id}`, item);
  }

  async deleteInventoryItem(id: number): Promise<ApiResponse<void>> {
    return this.delete<void>(`/inventory/${id}`);
  }

  async getLowStockItems(): Promise<ApiResponse<InventoryItem[]>> {
    return this.get<InventoryItem[]>('/inventory/low-stock');
  }

  // ============================================================================
  // EMPLOYEES
  // ============================================================================

  async getEmployees(params?: {
    page?: number;
    limit?: number;
    role?: string;
    is_active?: boolean;
  }): Promise<ApiResponse<Employee[]>> {
    return this.get<Employee[]>('/employees', params);
  }

  async createEmployee(employee: Omit<Employee, 'id'>): Promise<ApiResponse<Employee>> {
    return this.post<Employee>('/employees', employee);
  }

  async updateEmployee(id: number, employee: Partial<Employee>): Promise<ApiResponse<Employee>> {
    return this.put<Employee>(`/employees/${id}`, employee);
  }

  async deleteEmployee(id: number): Promise<ApiResponse<void>> {
    return this.delete<void>(`/employees/${id}`);
  }

  // ============================================================================
  // TAILORING ITEMS
  // ============================================================================

  async getTailoringItems(params?: {
    page?: number;
    limit?: number;
    category?: string;
    is_active?: boolean;
  }): Promise<ApiResponse<TailoringItem[]>> {
    return this.get<TailoringItem[]>('/tailoring-items', params);
  }

  async createTailoringItem(item: Omit<TailoringItem, 'id'>): Promise<ApiResponse<TailoringItem>> {
    return this.post<TailoringItem>('/tailoring-items', item);
  }

  async updateTailoringItem(id: number, item: Partial<TailoringItem>): Promise<ApiResponse<TailoringItem>> {
    return this.put<TailoringItem>(`/tailoring-items/${id}`, item);
  }

  async deleteTailoringItem(id: number): Promise<ApiResponse<void>> {
    return this.delete<void>(`/tailoring-items/${id}`);
  }

  // ============================================================================
  // TRANSACTIONS
  // ============================================================================

  async getIncomeTransactions(params?: {
    page?: number;
    limit?: number;
    start_date?: string;
    end_date?: string;
    category?: string;
  }): Promise<ApiResponse<any[]>> {
    return this.get<any[]>('/transactions/income', params);
  }

  async createIncomeTransaction(transaction: any): Promise<ApiResponse<any>> {
    return this.post<any>('/transactions/income', transaction);
  }

  async getExpenseTransactions(params?: {
    page?: number;
    limit?: number;
    start_date?: string;
    end_date?: string;
    category?: string;
  }): Promise<ApiResponse<any[]>> {
    return this.get<any[]>('/transactions/expenses', params);
  }

  async createExpenseTransaction(transaction: any): Promise<ApiResponse<any>> {
    return this.post<any>('/transactions/expenses', transaction);
  }

  // ============================================================================
  // STATISTICS & REPORTS
  // ============================================================================

  async getDashboardStats(): Promise<ApiResponse<any>> {
    return this.get<any>('/statistics/dashboard');
  }

  async getFinancialSummary(startDate: string, endDate: string): Promise<ApiResponse<any>> {
    return this.get<any>('/statistics/financial', { start_date: startDate, end_date: endDate });
  }

  async getReports(type: string, startDate: string, endDate: string): Promise<ApiResponse<any>> {
    return this.get<any>('/reports', { type, start_date: startDate, end_date: endDate });
  }

  // ============================================================================
  // SETTINGS
  // ============================================================================

  async getShopProfile(): Promise<ApiResponse<any>> {
    return this.get<any>('/settings/shop');
  }

  async updateShopProfile(profile: any): Promise<ApiResponse<any>> {
    return this.put<any>('/settings/shop', profile);
  }

  async getAppearanceSettings(): Promise<ApiResponse<any>> {
    return this.get<any>('/settings/appearance');
  }

  async updateAppearanceSettings(settings: any): Promise<ApiResponse<any>> {
    return this.put<any>('/settings/appearance', settings);
  }

  async getNotificationSettings(): Promise<ApiResponse<any>> {
    return this.get<any>('/settings/notifications');
  }

  async updateNotificationSettings(settings: any): Promise<ApiResponse<any>> {
    return this.put<any>('/settings/notifications', settings);
  }

  // ============================================================================
  // HEALTH CHECK
  // ============================================================================

  async healthCheck(): Promise<ApiResponse<any>> {
    return this.get<any>('/health');
  }
}

// Create singleton instance
export const apiClient = new ApiClient();

// Export for use in components
export default apiClient;
