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

// PPM (Asset Maintenance) Interfaces
export interface AssetMaintenance {
  name: string;
  company?: string;
  asset_name?: string;
  custom_asset_type?: string;
  asset_category?: string;
  custom_type_of_maintenance?: string;
  custom_asset_name?: string;
  item_code?: string;
  item_name?: string;
  maintenance_team?: string;
  custom_pm_schedule?: string;
  maintenance_manager?: string;
  maintenance_manager_name?: string;
  custom_warranty?: string;
  custom_warranty_status?: string;
  custom_service_contract?: number;
  custom_service_contract_status?: string;
  custom_frequency?: string;
  custom_total_amount?: number;
  custom_no_of_pms?: number;
  custom_price_per_pm?: number;
  creation?: string;
  modified?: string;
  owner?: string;
  modified_by?: string;
  docstatus?: number;
  idx?: number;
}

export interface AssetMaintenanceListResponse {
  asset_maintenances: AssetMaintenance[];
  total_count: number;
  limit: number;
  offset: number;
  has_more: boolean;
}

export interface MaintenanceTask {
  name: string;
  parent?: string;
  task?: string;
  task_name?: string;
  start_date?: string;
  end_date?: string;
  periodicity?: string;
  maintenance_type?: string;
  maintenance_status?: string;
  assign_to?: string;
  assign_to_name?: string;
  next_due_date?: string;
  last_completion_date?: string;
  [key: string]: any;
}

export interface ServiceCoverage {
  name: string;
  parent?: string;
  [key: string]: any;
}

export interface PPMFilters {
  company?: string;
  asset_name?: string;
  custom_asset_type?: string;
  maintenance_team?: string;
  custom_service_contract?: number;
  [key: string]: any;
}

export interface CreatePPMData {
  company?: string;
  asset_name?: string;
  custom_asset_type?: string;
  maintenance_team?: string;
  custom_frequency?: string;
  custom_total_amount?: number;
  [key: string]: any;
}

class PPMService {
  /**
   * Get list of asset maintenances (PPM schedules) with optional filters and pagination
   */
  async getAssetMaintenances(
    filters?: PPMFilters,
    fields?: string[],
    limit: number = 20,
    offset: number = 0,
    orderBy?: string
  ): Promise<AssetMaintenanceListResponse> {
    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_ASSET_MAINTENANCES}?${params.toString()}`;
    return apiService.apiCall<AssetMaintenanceListResponse>(endpoint);
  }

  /**
   * Get detailed information about a specific asset maintenance
   */
  async getAssetMaintenanceDetails(maintenanceName: string): Promise<AssetMaintenance> {
    const params = new URLSearchParams();
    params.append('maintenance_name', maintenanceName);
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_ASSET_MAINTENANCE_DETAILS}?${params.toString()}`;
    return apiService.apiCall<AssetMaintenance>(endpoint);
  }

  /**
   * Create a new asset maintenance (PPM schedule)
   */
  async createAssetMaintenance(data: CreatePPMData): Promise<{ success: boolean; asset_maintenance: AssetMaintenance; message?: string }> {
    const endpoint = `${API_CONFIG.ENDPOINTS.CREATE_ASSET_MAINTENANCE}`;
    return apiService.apiCall<{ success: boolean; asset_maintenance: AssetMaintenance; message?: string }>(
      endpoint,
      {
        method: 'POST',
        body: JSON.stringify({ maintenance_data: JSON.stringify(data) })
      }
    );
  }

  /**
   * Update an existing asset maintenance
   */
  async updateAssetMaintenance(
    maintenanceName: string,
    data: Partial<CreatePPMData>
  ): Promise<{ success: boolean; asset_maintenance: AssetMaintenance; message?: string }> {
    const endpoint = `${API_CONFIG.ENDPOINTS.UPDATE_ASSET_MAINTENANCE}`;
    return apiService.apiCall<{ success: boolean; asset_maintenance: AssetMaintenance; message?: string }>(
      endpoint,
      {
        method: 'POST',
        body: JSON.stringify({
          maintenance_name: maintenanceName,
          maintenance_data: JSON.stringify(data)
        })
      }
    );
  }

  /**
   * Delete an asset maintenance
   */
  async deleteAssetMaintenance(maintenanceName: string): Promise<{ success: boolean; message?: string }> {
    const endpoint = `${API_CONFIG.ENDPOINTS.DELETE_ASSET_MAINTENANCE}`;
    return apiService.apiCall<{ success: boolean; message?: string }>(
      endpoint,
      {
        method: 'POST',
        body: JSON.stringify({ maintenance_name: maintenanceName })
      }
    );
  }

  /**
   * Get all maintenance tasks for a specific asset maintenance
   */
  async getMaintenanceTasks(maintenanceName: string): Promise<{ maintenance_tasks: MaintenanceTask[]; total_count: number }> {
    const params = new URLSearchParams();
    params.append('maintenance_name', maintenanceName);
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_MAINTENANCE_TASKS}?${params.toString()}`;
    return apiService.apiCall<{ maintenance_tasks: MaintenanceTask[]; total_count: number }>(endpoint);
  }

  /**
   * Get service coverage for a specific asset maintenance
   */
  async getServiceCoverage(maintenanceName: string): Promise<{ service_coverage: ServiceCoverage[]; total_count: number }> {
    const params = new URLSearchParams();
    params.append('maintenance_name', maintenanceName);
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_SERVICE_COVERAGE}?${params.toString()}`;
    return apiService.apiCall<{ service_coverage: ServiceCoverage[]; total_count: number }>(endpoint);
  }

  /**
   * Get all maintenance schedules for a specific asset
   */
  async getMaintenancesByAsset(
    assetName: string,
    filters?: PPMFilters,
    limit: number = 20,
    offset: number = 0
  ): Promise<AssetMaintenanceListResponse> {
    const params = new URLSearchParams();
    params.append('asset_name', assetName);
    
    if (filters) {
      params.append('filters', JSON.stringify(filters));
    }
    
    params.append('limit', limit.toString());
    params.append('offset', offset.toString());
    
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_MAINTENANCES_BY_ASSET}?${params.toString()}`;
    return apiService.apiCall<AssetMaintenanceListResponse>(endpoint);
  }

  /**
   * Get all asset maintenances with active service contracts
   */
  async getActiveServiceContracts(
    filters?: PPMFilters,
    limit: number = 20,
    offset: number = 0
  ): Promise<AssetMaintenanceListResponse> {
    const params = new URLSearchParams();
    
    if (filters) {
      params.append('filters', JSON.stringify(filters));
    }
    
    params.append('limit', limit.toString());
    params.append('offset', offset.toString());
    
    const endpoint = `${API_CONFIG.ENDPOINTS.GET_ACTIVE_SERVICE_CONTRACTS}?${params.toString()}`;
    return apiService.apiCall<AssetMaintenanceListResponse>(endpoint);
  }
}

const ppmService = new PPMService();
export default ppmService;

