<template>
  <el-select
    :model-value="currentMode"
    size="small"
    class="veh-maint-select"
    :class="toneClass"
    :disabled="!canWrite"
    :teleported="true"
    @change="onChange"
    @click.stop
  >
    <el-option
      v-for="opt in MAINTENANCE_OPTIONS"
      :key="opt.value"
      :label="opt.label"
      :value="opt.value"
    />
  </el-select>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { VehicleCardModel } from '@/types/car'
import type { VehicleMaintenanceMode } from '@/api/vehicleOps'
import {
  MAINTENANCE_OPTIONS,
  confirmAndApplyMaintenance
} from '@/composables/useVehicleMaintenanceActions'

const props = defineProps<{
  vehicle: VehicleCardModel
  canWrite?: boolean
}>()

const emit = defineEmits<{ changed: [] }>()

const currentMode = ref<VehicleMaintenanceMode>(props.vehicle.maintenanceMode ?? 'online')

watch(
  () => props.vehicle.maintenanceMode,
  (m) => {
    currentMode.value = m ?? 'online'
  }
)

const toneClass = computed(() => {
  const m = currentMode.value
  if (m === 'blown' || m === 'offline') return 'tone-danger'
  if (m === 'repair') return 'tone-warning'
  return 'tone-online'
})

async function onChange(mode: VehicleMaintenanceMode) {
  const prev = props.vehicle.maintenanceMode ?? 'online'
  if (mode === prev) return

  const rawId = props.vehicle.rawId ?? parseInt(props.vehicle.id.replace(/\D/g, ''), 10)
  const ok = await confirmAndApplyMaintenance(rawId, mode, prev)
  if (ok) {
    currentMode.value = mode
    emit('changed')
  } else {
    currentMode.value = prev
  }
}
</script>

<style scoped>
.veh-maint-select {
  width: 108px;
}

.veh-maint-select :deep(.el-select__wrapper) {
  background: rgba(0, 0, 0, 0.22);
  border-color: rgba(255, 255, 255, 0.18);
  box-shadow: none;
  min-height: 28px;
  padding: 0 8px;
}

.veh-maint-select :deep(.el-select__selected-item),
.veh-maint-select :deep(.el-select__placeholder) {
  color: rgba(255, 255, 255, 0.92);
  font-size: 12px;
  font-weight: 600;
}

.veh-maint-select :deep(.el-select__caret) {
  color: rgba(255, 255, 255, 0.65);
}

.veh-maint-select.tone-online :deep(.el-select__wrapper) {
  border-color: rgba(var(--mg-status-success-rgb, 34, 197, 94), 0.45);
}
.veh-maint-select.tone-warning :deep(.el-select__wrapper) {
  border-color: rgba(var(--mg-status-warning-rgb, 245, 158, 11), 0.5);
}
.veh-maint-select.tone-danger :deep(.el-select__wrapper) {
  border-color: rgba(var(--mg-status-danger-rgb, 239, 68, 68), 0.5);
}

.veh-maint-select.is-disabled :deep(.el-select__wrapper) {
  opacity: 0.65;
}
</style>
