import apiService from './apiService';
import API_CONFIG from '../config/api';

// Work Order Interfaces
export interface WorkOrder {
  completion_date: string;
  name: string;
  company?: string;
  naming_series?: string;
  work_order_type?: string;
  asset_type?: string;
  manufacturer?: string;
  serial_number?: string;
  custom_serial_number?: string;
  custom_manufacturer?: string;
  custom_priority_?: string;
  asset?: string;
  custom_maintenance_manager?: string;
  department?: string;
  repair_status?: string;
  asset_name?: string;
  supplier?: string;
  custom_pending_reason?: string;
  model?: string;
  custom_site_contractor?: string;
  custom_subcontractor?: string;
  custom_service_agreement?: string;
  custom_service_coverage?: string;
  custom_start_date?: string;
  custom_end_date?: string;
  custom_total_amount?: number;
  warranty?: string;
  service_contract?: string;
  covering_spare_parts?: string;
  spare_parts_labour?: string;
  covering_labour?: string;
  ppm_only?: number;
  failure_date?: string;
  total_hours_spent?: number;
  job_completed?: string;
  custom_difference?: number;
  custom_vendors_hrs?: number;
  custom_deadline_date?: string;
  custom_diffrence?: number;
  feedback_rating?: number;
  first_responded_on?: string;
  penalty?: number;
  custom_assigned_supervisor?: string;
  custom_moh_supervisor?: string;
  stock_consumption?: number;
  need_procurement?: number;
  repair_cost?: number;
  total_repair_cost?: number;
  capitalize_repair_cost?: number;
  increase_in_asset_life?: number;
  description?: string;
  actions_performed?: string;
  bio_med_dept?: string;
  workflow_state?: string;
  creation?: string;
  modified?: string;
  owner?: string;
  modified_by?: string;
  docstatus?: number;
  idx?: number;
  stock_items?: StockItem[];
  site_name?: string;
  custom_assign_to_contractor?: string;
}

export interface StockItem {
  item_code: string;
  item_name?: string;
  warehouse: string;
  consumed_quantity: number;
  valuation_rate: number;
  custom_available_stock: number;
  total_value: number;
}

export interface WorkOrderListResponse {
  work_orders: WorkOrder[];
  total_count: number;
  limit: number;
  offset: number;
  has_more: boolean;
}

export interface WorkOrderFilters {
  company?: string;
  department?: string;
  work_order_type?: string;
  repair_status?: string;
  workflow_state?: string;
  asset?: string;
  custom_manufacturer?: string;
  supplier?: string;
  custom_serial_number?: string;
  custom_priority_?: string;
  [key: string]: any;
}

export interface WorkOrderFilterOptions {
  companies: string[];
  departments: string[];
  work_order_types: string[];
  repair_statuses: string[];
  workflow_states: string[];
  manufacturers: string[];
  suppliers: string[];
  priorities: string[];
}

export interface WorkOrderStats {
  total_work_orders: number;
  by_status: Record<string, number>;
  by_company: Record<string, number>;
  by_type: Record<string, number>;
  by_priority: Record<string, number>;
  total_repair_cost: number;
  avg_resolution_time: number;
}

export interface CreateWorkOrderData {
  company?: string;
  work_order_type?: string;
  asset?: string;
  asset_name?: string;
  description?: string;
  repair_status?: string;
  workflow_state?: string;
  department?: string;
  custom_priority_?: string;
  custom_manufacturer?: string;
  supplier?: string;
  custom_serial_number?: string;
  [key: string]: any;
}

class WorkOrderService {
  /**
   * Get list of work orders with optional filters and pagination
   */
  async getWorkOrders(
    filters?: WorkOrderFilters,
    fields?: string[],
    limit: number = 20,
    offset: number = 0,
    orderBy?: string
  ): Promise<WorkOrderListResponse> {
    const params = new URLSearchParams();
    
    if (filters) {
      params.append('filters', JSON.stringify(filters));
    }
    
    if (fields && fields.length > 0) {
      params.append('fields', JSON.stringify(fields));
    }
    
    params.append('limit', limit.toString());
    params.append('offset', offset.toString());
    
    if (orderBy) {
      params.append('order_by', orderBy);
    }
    
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_WORK_ORDERS}?${params.toString()}`;
    return apiService.apiCall<WorkOrderListResponse>(endpoint);
  }

  /**
   * Get detailed information about a specific work order
   */
  async getWorkOrderDetails(workOrderName: string): Promise<WorkOrder> {
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_WORK_ORDER_DETAILS}?work_order_name=${encodeURIComponent(workOrderName)}`;
    return apiService.apiCall<WorkOrder>(endpoint);
  }

  /**
   * Create a new work order
   */
  async createWorkOrder(workOrderData: CreateWorkOrderData): Promise<{ success: boolean; work_order: WorkOrder; message: string }> {
    return apiService.apiCall(API_CONFIG.ENDPOINTS.CREATE_WORK_ORDER, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ work_order_data: workOrderData })
    });
  }

  /**
   * Update an existing work order
   */
  async updateWorkOrder(
    workOrderName: string,
    workOrderData: Partial<CreateWorkOrderData>
  ): Promise<{ success: boolean; work_order: WorkOrder; message: string }> {
    return apiService.apiCall(API_CONFIG.ENDPOINTS.UPDATE_WORK_ORDER, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        work_order_name: workOrderName,
        work_order_data: workOrderData
      })
    });
  }

  /**
   * Delete a work order
   */
  async deleteWorkOrder(workOrderName: string): Promise<{ success: boolean; message: string }> {
    return apiService.apiCall(API_CONFIG.ENDPOINTS.DELETE_WORK_ORDER, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ work_order_name: workOrderName })
    });
  }

  /**
   * Update work order status
   */
  async updateWorkOrderStatus(
    workOrderName: string,
    repairStatus?: string,
    workflowState?: string
  ): Promise<{ success: boolean; work_order: WorkOrder; message: string }> {
    return apiService.apiCall(API_CONFIG.ENDPOINTS.UPDATE_WORK_ORDER_STATUS, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        work_order_name: workOrderName,
        repair_status: repairStatus,
        workflow_state: workflowState
      })
    });
  }

  /**
   * Get available filter options
   */
  async getWorkOrderFilters(): Promise<WorkOrderFilterOptions> {
    return apiService.apiCall<WorkOrderFilterOptions>(API_CONFIG.ENDPOINTS.GET_WORK_ORDER_FILTERS);
  }

  /**
   * Get work order statistics
   */
  async getWorkOrderStats(): Promise<WorkOrderStats> {
    return apiService.apiCall<WorkOrderStats>(API_CONFIG.ENDPOINTS.GET_WORK_ORDER_STATS);
  }

  /**
   * Search work orders by keyword
   */
  async searchWorkOrders(searchTerm: string, limit: number = 10): Promise<WorkOrder[]> {
    const endpoint = `${API_CONFIG.ENDPOINTS.SEARCH_WORK_ORDERS}?search_term=${encodeURIComponent(searchTerm)}&limit=${limit}`;
    return apiService.apiCall<WorkOrder[]>(endpoint);
  }

  /**
   * Submit a work order document (changes docstatus from 0 to 1)
   */
  async submitWorkOrder(workOrderName: string): Promise<{ message: string }> {
    return apiService.apiCall('/api/method/frappe.client.submit', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        doc: {
          doctype: 'Asset Repair',
          name: workOrderName
        }
      })
    });
  }

  /**
   * Cancel a work order document (changes docstatus from 1 to 2)
   */
  async cancelWorkOrder(workOrderName: string): Promise<{ message: string }> {
    return apiService.apiCall('/api/method/frappe.client.cancel', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        doc: {
          doctype: 'Asset Repair',
          name: workOrderName
        }
      })
    });
  }

  /**
   * Get work orders for a specific asset
   */
  async getWorkOrdersByAsset(assetName: string, limit: number = 50): Promise<WorkOrder[]> {
    const filters: WorkOrderFilters = { asset: assetName };
    const response = await this.getWorkOrders(filters, undefined, limit, 0, 'creation desc');
    return response.work_orders;
  }

  /**
   * Get open work orders (not completed or cancelled)
   */
  async getOpenWorkOrders(limit: number = 50): Promise<WorkOrder[]> {
    const filters: WorkOrderFilters = { 
      repair_status: ['not in', ['Completed', 'Cancelled']] as any
    };
    const response = await this.getWorkOrders(filters, undefined, limit, 0, 'creation desc');
    return response.work_orders;
  }

  /**
   * Get work orders by priority
   */
  async getWorkOrdersByPriority(priority: string, limit: number = 50): Promise<WorkOrder[]> {
    const filters: WorkOrderFilters = { custom_priority_: priority };
    const response = await this.getWorkOrders(filters, undefined, limit, 0, 'creation desc');
    return response.work_orders;
  }
}

// Create and export singleton instance
const workOrderService = new WorkOrderService();
export default workOrderService;