import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Vehicle, VehicleStatus } from '@/types'
import { getVehicleList } from '@/api/vehicle'

interface VehicleRow {
  vehicleId?: number | string
  plateNo?: string
  vehicleType?: string
  status?: string
  driverName?: string
  driverPhone?: string
  size?: string
  loadCapacity?: string
  capacity?: string
  purchaseDate?: string
  mileage?: number
}

function mapVehicleStatus(status?: string): VehicleStatus {
  const map: Record<string, VehicleStatus> = {
    idle: 'available',
    available: 'available',
    in_use: 'in_use',
    working: 'in_use',
    maintenance: 'maintenance',
  }
  return map[status || ''] || 'available'
}

function mapVehicleRow(row: VehicleRow): Vehicle {
  return {
    id: String(row.vehicleId ?? ''),
    plateNumber: row.plateNo || '',
    type: row.vehicleType || '',
    status: mapVehicleStatus(row.status),
    driver: row.driverName || undefined,
    driverPhone: row.driverPhone || undefined,
    size: row.size,
    loadCapacity: row.loadCapacity,
    capacity: row.capacity,
    purchaseDate: row.purchaseDate,
    mileage: row.mileage,
  }
}

export const useVehicleStore = defineStore('vehicle', () => {
  const vehicles = ref<Vehicle[]>([])
  const filterStatus = ref<VehicleStatus | 'all'>('all')
  const loading = ref(false)

  const filteredVehicles = computed(() => {
    if (filterStatus.value === 'all') return vehicles.value
    return vehicles.value.filter((v) => v.status === filterStatus.value)
  })

  const availableVehicles = computed(() => vehicles.value.filter((v) => v.status === 'available'))
  const inUseCount = computed(() => vehicles.value.filter((v) => v.status === 'in_use').length)
  const maintenanceCount = computed(() => vehicles.value.filter((v) => v.status === 'maintenance').length)

  async function fetchVehicles() {
    loading.value = true
    try {
      const res: any = await getVehicleList(1, 100)
      const rows: VehicleRow[] = res.rows || []
      vehicles.value = rows.map(mapVehicleRow)
    } finally {
      loading.value = false
    }
  }

  function setFilter(status: VehicleStatus | 'all') {
    filterStatus.value = status
  }

  function updateVehicleStatus(vehicleId: string, status: VehicleStatus) {
    const vehicle = vehicles.value.find((v) => v.id === vehicleId)
    if (vehicle) {
      vehicle.status = status
    }
  }

  return {
    vehicles,
    filterStatus,
    filteredVehicles,
    availableVehicles,
    inUseCount,
    maintenanceCount,
    loading,
    fetchVehicles,
    setFilter,
    updateVehicleStatus,
  }
})
