<template>
  <Loading v-if="pageLoading" text="加载中..." />
  <scroll-view v-else scroll-y class="page-scroll">
    <view :class="['page-content', elderClass]">
      <!-- Tab 筛选 -->
      <scroll-view scroll-x class="tab-bar">
        <view
          v-for="tab in FILTER_TABS"
          :key="tab.key"
          :class="['tab-chip', { 'tab-chip--active': activeFilter === tab.key }]"
          @tap="handleFilterChange(tab.key)"
        >
          <text class="tab-chip__text">{{ tab.label }}</text>
        </view>
      </scroll-view>

      <!-- 我的统计 -->
      <view v-if="stats" class="section">
        <text class="section-title">我的统计</text>
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-item__value">{{ stats.pending }}</text>
            <text class="stat-item__label">待处理</text>
          </view>
          <view class="stat-item stat-item--warn">
            <text class="stat-item__value">{{ stats.overdue }}</text>
            <text class="stat-item__label">紧急事项</text>
          </view>
          <view class="stat-item stat-item--success">
            <text class="stat-item__value">{{ stats.completed_today }}</text>
            <text class="stat-item__label">今日完成</text>
          </view>
        </view>
      </view>

      <!-- 团队概览 -->
      <view v-if="team" class="section">
        <text class="section-title">团队概览</text>
        <view class="team-row">
          <text class="team-row__label">团队待处理</text>
          <text class="team-row__value">{{ team.total_pending }}</text>
        </view>
        <view class="team-row">
          <text class="team-row__label">平均响应时间</text>
          <text class="team-row__value">{{ formatResponseTime(team.avg_response_time) }}</text>
        </view>
        <view v-if="team.members.length > 0" class="team-members">
          <view
            v-for="member in team.members"
            :key="member.user_id"
            class="member-item"
          >
            <text class="member-item__name">{{ member.user_name }}</text>
            <text class="member-item__role">{{ member.role }}</text>
            <text
              :class="['member-item__tasks', member.active_tasks > 0 ? 'member-item__tasks--active' : '']"
            >
              {{ member.active_tasks }} 项
            </text>
          </view>
        </view>
      </view>

      <!-- 我的患者 -->
      <view class="section">
        <text class="section-title">我的患者</text>
        <EmptyState v-if="patients.length === 0" icon="👥" title="暂无患者" />
        <view v-else class="patient-cards">
          <view
            v-for="p in filteredPatients"
            :key="p.patient_id"
            class="patient-card"
            @tap="goPatientDetail(p.patient_id)"
          >
            <view class="patient-card__header">
              <text class="patient-card__name">{{ p.patient_name }}</text>
              <text v-if="p.bed_number" class="patient-card__bed">
                {{ p.bed_number }}床
              </text>
            </view>
            <view v-if="p.primary_diagnosis" class="patient-card__diagnosis">
              <text class="patient-card__diagnosis-text">{{ p.primary_diagnosis }}</text>
            </view>
            <view class="patient-card__footer">
              <view v-if="p.open_action_count > 0" class="patient-card__actions">
                <text class="patient-card__actions-text">
                  {{ p.open_action_count }} 项待办
                </text>
              </view>
              <text v-if="p.care_plan_status" class="patient-card__plan">
                {{ p.care_plan_status }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { useElderClass } from '@/composables/useElderClass'
import {
  getWorkbenchStats,
  getTeamOverview,
  getMyPatients,
} from '@/services/doctor/actionInbox'
import Loading from '@/components/Loading.vue'
import EmptyState from '@/components/EmptyState.vue'

interface WorkbenchStats {
  pending: number
  in_progress: number
  completed_today: number
  overdue: number
}

interface TeamMember {
  user_id: string
  user_name: string
  role: string
  active_tasks: number
}

interface TeamOverviewData {
  team_name: string
  members: TeamMember[]
  total_pending: number
  avg_response_time: number
}

interface NursePatientSummary {
  patient_id: string
  patient_name: string
  bed_number?: string
  primary_diagnosis?: string
  care_plan_status?: string
  open_action_count: number
}

const FILTER_TABS = [
  { key: '', label: '全部' },
  { key: 'pending', label: '待处理' },
  { key: 'urgent', label: '紧急' },
] as const

const { elderClass } = useElderClass()

const stats = ref<WorkbenchStats | null>(null)
const team = ref<TeamOverviewData | null>(null)
const patients = ref<NursePatientSummary[]>([])
const activeFilter = ref('')
const pageLoading = ref(true)

const filteredPatients = computed(() => {
  const list = patients.value
  if (activeFilter.value === 'pending') {
    return list.filter((p) => p.open_action_count > 0)
  }
  if (activeFilter.value === 'urgent') {
    return list.filter((p) => p.open_action_count >= 3)
  }
  return list
})

function formatResponseTime(minutes: number): string {
  if (minutes < 60) return `${Math.round(minutes)} 分钟`
  const hours = Math.floor(minutes / 60)
  const mins = Math.round(minutes % 60)
  return mins > 0 ? `${hours} 小时 ${mins} 分钟` : `${hours} 小时`
}

async function loadData() {
  pageLoading.value = true
  try {
    const [s, t, p] = await Promise.all([
      getWorkbenchStats(true),
      getTeamOverview(),
      getMyPatients(),
    ])
    stats.value = s
    team.value = t as TeamOverviewData
    patients.value = p || []
  } catch {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    pageLoading.value = false
  }
}

function handleFilterChange(key: string) {
  activeFilter.value = key
}

function goPatientDetail(patientId: string) {
  uni.navigateTo({
    url: `/pages-sub/doctor/patients/detail/index?id=${patientId}`,
  })
}

onShow(() => {
  loadData()
})

onPullDownRefresh(() => {
  loadData().finally(() => {
    uni.stopPullDownRefresh()
  })
})
</script>

<style lang="scss" scoped>
.page-scroll {
  height: 100vh;
  background: $bg;
}

.page-content {
  padding: 24px;
  padding-bottom: 120px;
}

// ── 标签栏 ──
.tab-bar {
  white-space: nowrap;
  margin-bottom: 24px;
  width: 100%;
}

.tab-chip {
  display: inline-flex;
  align-items: center;
  padding: 10px 28px;
  min-height: $touch-min;
  border-radius: $r-pill;
  background: $card;
  box-shadow: $shadow-sm;
  margin-right: 12px;

  &--active {
    background: $pri;

    .tab-chip__text {
      color: $card;
    }
  }

  &__text {
    font-size: var(--tk-font-body);
    color: $tx2;
    font-weight: 500;
  }
}

// ── 通用区块 ──
.section {
  background: $card;
  border-radius: $r-lg;
  padding: 28px;
  margin-bottom: 20px;
  box-shadow: $shadow-sm;
}

.section-title {
  @include section-title;
}

// ── 统计网格 ──
.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}

.stat-item {
  text-align: center;
  background: $pri-l;
  border-radius: $r;
  padding: 20px 12px;

  &--warn {
    background: $wrn-l;
  }

  &--success {
    background: $acc-l;
  }

  &__value {
    @include serif-number;
    font-size: var(--tk-font-num-lg);
    font-weight: 700;
    color: $pri;
    display: block;
    margin-bottom: 6px;

    .stat-item--warn & {
      color: $wrn;
    }

    .stat-item--success & {
      color: $acc;
    }
  }

  &__label {
    font-size: var(--tk-font-body-sm);
    color: $tx2;
  }
}

// ── 团队概览 ──
.team-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 0;
  border-bottom: 1px solid $bd-l;

  &:last-of-type {
    border-bottom: none;
  }

  &__label {
    font-size: var(--tk-font-body);
    color: $tx2;
  }

  &__value {
    @include serif-number;
    font-size: var(--tk-font-body-lg);
    font-weight: 600;
    color: $tx;
  }
}

.team-members {
  margin-top: 16px;
  border-top: 1px solid $bd-l;
  padding-top: 16px;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid $bd-l;

  &:last-child {
    border-bottom: none;
  }

  &__name {
    font-size: var(--tk-font-body);
    color: $tx;
    font-weight: 500;
    flex: 1;
  }

  &__role {
    font-size: var(--tk-font-body-sm);
    color: $tx3;
    margin-right: 16px;
  }

  &__tasks {
    font-size: var(--tk-font-body-sm);
    color: $tx3;

    &--active {
      color: $wrn;
      font-weight: 600;
    }
  }
}

// ── 患者卡片 ──
.patient-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.patient-card {
  background: $bg;
  border-radius: $r;
  padding: 20px;

  &:active {
    background: $bd-l;
  }

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  &__name {
    font-size: var(--tk-font-body-lg);
    font-weight: 600;
    color: $tx;
  }

  &__bed {
    font-size: var(--tk-font-body-sm);
    color: $tx2;
    background: $card;
    padding: 4px 12px;
    border-radius: $r-xs;
  }

  &__diagnosis {
    margin-bottom: 10px;
  }

  &__diagnosis-text {
    font-size: var(--tk-font-body);
    color: $tx2;
  }

  &__footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &__actions {
    background: $wrn-l;
    padding: 4px 12px;
    border-radius: $r-xs;
  }

  &__actions-text {
    font-size: var(--tk-font-body-sm);
    color: $wrn;
    font-weight: 500;
  }

  &__plan {
    font-size: var(--tk-font-body-sm);
    color: $tx3;
  }
}
</style>
