<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { roomApi, reservationApi } from '@/api/room.js'

const rooms = ref([])
const loading = ref(false)
const detailVisible = ref(false)
const detailRoom = ref(null)
const filterStatus = ref('')

const statusConfig = {
  available:    { label: '空置',  color: 'bg-emerald-50 border-emerald-200', badge: 'bg-emerald-500', text: 'text-emerald-700', dot: 'bg-emerald-400' },
  occupied:     { label: '在住',  color: 'bg-blue-50 border-blue-200',       badge: 'bg-blue-500',    text: 'text-blue-700',    dot: 'bg-blue-400' },
  cleaning:     { label: '保洁',  color: 'bg-amber-50 border-amber-200',     badge: 'bg-amber-500',   text: 'text-amber-700',   dot: 'bg-amber-400' },
  maintenance:  { label: '维护',  color: 'bg-gray-50 border-gray-200',       badge: 'bg-gray-400',    text: 'text-gray-600',    dot: 'bg-gray-400' }
}

const statusOptions = Object.entries(statusConfig).map(([k, v]) => ({ value: k, label: v.label }))

const filteredRooms = computed(() => {
  if (!filterStatus.value) return rooms.value
  return rooms.value.filter(r => r.status === filterStatus.value)
})

const summary = computed(() => {
  const map = {}
  for (const k of Object.keys(statusConfig)) map[k] = 0
  for (const r of rooms.value) { if (map[r.status] !== undefined) map[r.status]++ }
  return map
})

async function fetchRooms() {
  loading.value = true
  try {
    const res = await roomApi.getList({ per_page: 200 })
    rooms.value = res.data?.list || res.data?.data || []
  } catch (e) { console.error(e) }
  finally { loading.value = false }
}

async function openDetail(room) {
  detailRoom.value = room
  if (room.status === 'occupied') {
    try {
      const res = await reservationApi.getList({ room_id: room.id, status: 1, per_page: 1 })
      const list = res.data?.list || res.data?.data || []
      detailRoom.value = { ...room, currentReservation: list[0] || null }
    } catch (e) { console.error(e) }
  }
  detailVisible.value = true
}

async function handleStatusChange(room, newStatus) {
  try {
    await roomApi.updateStatus(room.id, { status: newStatus })
    ElMessage.success('房态已更新')
    fetchRooms()
  } catch (e) { console.error(e) }
}

onMounted(() => fetchRooms())
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- Summary Stats -->
    <div class="grid grid-cols-4 gap-4">
      <div v-for="(cfg, key) in statusConfig" :key="key"
        class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center gap-3 cursor-pointer transition-all hover:shadow-md"
        :class="filterStatus === key ? 'ring-2 ring-rose-400' : ''"
        @click="filterStatus = filterStatus === key ? '' : key"
      >
        <div class="w-10 h-10 rounded-xl flex items-center justify-center" :class="cfg.badge + '/20'">
          <span class="w-4 h-4 rounded-full inline-block" :class="cfg.dot"></span>
        </div>
        <div>
          <div class="text-2xl font-bold" :class="cfg.text">{{ summary[key] }}</div>
          <div class="text-xs text-gray-500">{{ cfg.label }}</div>
        </div>
      </div>
    </div>

    <!-- Board -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-2">
          <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <span class="font-medium text-gray-700">房态看板</span>
          <span class="text-xs text-gray-400 ml-2">点击统计卡片可按状态筛选，点击房间卡片查看详情</span>
        </div>
        <div class="flex items-center gap-2">
          <el-select v-model="filterStatus" placeholder="全部状态" clearable style="width:130px">
            <el-option v-for="s in statusOptions" :key="s.value" :label="s.label" :value="s.value" />
          </el-select>
          <el-button @click="fetchRooms" :loading="loading">刷新</el-button>
        </div>
      </div>

      <div v-loading="loading" class="p-5">
        <div v-if="filteredRooms.length === 0" class="py-16 text-center text-gray-400">暂无房间数据</div>
        <div v-else class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
          <div
            v-for="room in filteredRooms"
            :key="room.id"
            class="rounded-xl border-2 p-3 cursor-pointer transition-all hover:-translate-y-0.5 hover:shadow-md select-none"
            :class="statusConfig[room.status]?.color || 'bg-gray-50 border-gray-200'"
            @click="openDetail(room)"
          >
            <!-- Room number + status dot -->
            <div class="flex items-center justify-between mb-2">
              <span class="font-bold text-gray-800 text-sm">{{ room.number }}</span>
              <span class="w-2.5 h-2.5 rounded-full" :class="statusConfig[room.status]?.dot || 'bg-gray-400'"></span>
            </div>
            <!-- Room type -->
            <div class="text-xs text-gray-500 mb-1 truncate">{{ room.room_type?.name || room.type_name || '-' }}</div>
            <!-- Status label -->
            <div class="text-xs font-medium" :class="statusConfig[room.status]?.text || 'text-gray-500'">
              {{ statusConfig[room.status]?.label || room.status }}
            </div>
            <!-- Customer name if occupied -->
            <div v-if="room.status === 'occupied' && (room.customer_name || room.current_customer)" class="text-xs text-blue-600 mt-1 truncate font-medium">
              {{ room.customer_name || room.current_customer }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Room Detail Drawer -->
    <el-drawer v-model="detailVisible" title="房间详情" size="400px">
      <template v-if="detailRoom">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="房间号">{{ detailRoom.number }}</el-descriptions-item>
          <el-descriptions-item label="房型">{{ detailRoom.room_type?.name || detailRoom.type_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="楼层">{{ detailRoom.floor || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="{ available: 'success', occupied: 'primary', cleaning: 'warning', maintenance: 'info' }[detailRoom.status]" size="small">
              {{ statusConfig[detailRoom.status]?.label || detailRoom.status }}
            </el-tag>
          </el-descriptions-item>
          <template v-if="detailRoom.status === 'occupied' && detailRoom.currentReservation">
            <el-descriptions-item label="在住客户">{{ detailRoom.currentReservation.customer?.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="入住日期">{{ detailRoom.currentReservation.check_in_date || '-' }}</el-descriptions-item>
            <el-descriptions-item label="预计离店">{{ detailRoom.currentReservation.check_out_date || '-' }}</el-descriptions-item>
          </template>
        </el-descriptions>

        <div class="mt-4">
          <div class="text-sm font-medium text-gray-600 mb-2">快速变更房态</div>
          <div class="flex flex-wrap gap-2">
            <el-button
              v-for="s in statusOptions"
              :key="s.value"
              size="small"
              :disabled="detailRoom.status === s.value"
              @click="handleStatusChange(detailRoom, s.value)"
            >{{ s.label }}</el-button>
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
