import { api } from './client';
import type { ApiResponse, PaginatedResult, BaseFilters, ServiceOrderStatus } from '../../types';

// Types
export interface ServiceOrder {
  id: string;
  tenant_id: string;
  order_number: string;
  customer_id: string;
  customer_name: string;
  vehicle_id: string;
  vehicle_info: string;
  status: ServiceOrderStatus;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  received_at: string;
  promised_at: string | null;
  mechanic_id: string | null;
  mechanic_name: string | null;
  bay_id: string | null;
  bay_name: string | null;
  symptoms: string;
  notes: string | null;
  labor_total: number;
  parts_total: number;
  tax: number;
  grand_total: number;
  created_at: string;
  updated_at: string | null;
}

export interface ServiceOrderItem {
  id: string;
  order_id: string;
  item_type: 'service' | 'part';
  service_id: string | null;
  part_id: string | null;
  description: string;
  quantity: number;
  unit_price: number;
  discount: number;
  subtotal: number;
  actual_hours: number | null;
  performed_by: string | null;
}

export interface CreateServiceOrderRequest {
  customer_id: string;
  vehicle_id: string;
  symptoms: string;
  priority?: 'low' | 'medium' | 'high' | 'urgent';
  promised_at?: string;
  mechanic_id?: string;
  bay_id?: string;
}

export interface ServiceOrderFilters extends BaseFilters {
  status?: ServiceOrderStatus;
  priority?: string;
  mechanic_id?: string;
  bay_id?: string;
  customer_id?: string;
  vehicle_id?: string;
}

// API
export const serviceOrdersApi = {
  // List orders with filters
  list: (filters?: ServiceOrderFilters) =>
    api.get<ApiResponse<PaginatedResult<ServiceOrder>>>('/service-orders', {
      params: filters,
    }),

  // Get single order
  getById: (id: string) =>
    api.get<ApiResponse<ServiceOrder>>(`/service-orders/${id}`),

  // Create new order
  create: (data: CreateServiceOrderRequest) =>
    api.post<ApiResponse<ServiceOrder>>('/service-orders', data),

  // Update order
  update: (id: string, data: Partial<ServiceOrder>) =>
    api.patch<ApiResponse<ServiceOrder>>(`/service-orders/${id}`, data),

  // Change status
  changeStatus: (id: string, status: ServiceOrderStatus, notes?: string) =>
    api.post<ApiResponse<ServiceOrder>>(`/service-orders/${id}/status`, {
      status,
      notes,
    }),

  // Assign mechanic and bay
  assign: (id: string, mechanicId: string, bayId: string) =>
    api.post<ApiResponse<ServiceOrder>>(`/service-orders/${id}/assign`, {
      mechanic_id: mechanicId,
      bay_id: bayId,
    }),

  // Get order items
  getItems: (orderId: string) =>
    api.get<ApiResponse<ServiceOrderItem[]>>(`/service-orders/${orderId}/items`),

  // Add item to order
  addItem: (orderId: string, item: Partial<ServiceOrderItem>) =>
    api.post<ApiResponse<ServiceOrderItem>>(`/service-orders/${orderId}/items`, item),

  // Remove item from order
  removeItem: (orderId: string, itemId: string) =>
    api.delete<ApiResponse<null>>(`/service-orders/${orderId}/items/${itemId}`),

  // Close order
  close: (id: string, finalOdometer: number) =>
    api.post<ApiResponse<ServiceOrder>>(`/service-orders/${id}/close`, {
      final_odometer: finalOdometer,
    }),

  // Get kanban view data
  getKanbanView: () =>
    api.get<ApiResponse<Record<ServiceOrderStatus, ServiceOrder[]>>>('/service-orders/kanban'),

  // Get order history
  getHistory: (vehicleId: string) =>
    api.get<ApiResponse<ServiceOrder[]>>(`/vehicles/${vehicleId}/service-history`),

  // Get dashboard stats
  getStats: () =>
    api.get<ApiResponse<DashboardStats>>('/service-orders/stats'),
};

// Dashboard Stats type
export interface DashboardStats {
  totalOrders: number;
  pendingOrders: number;
  inProgressOrders: number;
  completedToday: number;
  totalRevenue: number;
  averageTicket: number;
}
