<script lang="ts" setup>
import { computed } from 'vue';

import {
  Avatar,
  Descriptions,
  DescriptionsItem,
  Image,
  Popover,
} from 'ant-design-vue';

import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';

import { resolveAvatarUrl } from '../utils/inputUser';
import {
  doctorCertImages,
  doctorDepartName,
  doctorTitleName,
  getAuditStatusText,
  getDoctorTypeText,
  getSignTypeText,
  isDoctorPending,
  normalizeDoctorRecord,
} from '../utils/doctorInputDisplay';

const props = withDefaults(
  defineProps<{
    doctors: Record<string, any>[];
    selectedIds?: number[];
    selectable?: boolean;
    onlyPendingSelectable?: boolean;
  }>(),
  {
    selectedIds: () => [],
    selectable: false,
    onlyPendingSelectable: true,
  },
);

const emit = defineEmits<{
  'update:selectedIds': [ids: number[]];
}>();

const normalizedDoctors = computed(() =>
  (props.doctors || []).map((d) => normalizeDoctorRecord({ ...d })),
);

function doctorId(doc: Record<string, any>) {
  return Number(doc.id) || 0;
}

function isSelected(doc: Record<string, any>) {
  return props.selectedIds.includes(doctorId(doc));
}

function canToggle(doc: Record<string, any>) {
  if (!props.selectable) return false;
  if (props.onlyPendingSelectable && !isDoctorPending(doc)) return false;
  return doctorId(doc) > 0;
}

function toggleSelect(doc: Record<string, any>) {
  if (!canToggle(doc)) return;
  const id = doctorId(doc);
  const next = [...props.selectedIds];
  const idx = next.indexOf(id);
  if (idx >= 0) {
    next.splice(idx, 1);
  } else {
    next.push(id);
  }
  emit('update:selectedIds', next);
}

function cardClass(doc: Record<string, any>) {
  const base =
    'flex h-full flex-col rounded border p-3 transition-colors';
  if (!props.selectable) {
    return `${base} cursor-default border-gray-100`;
  }
  if (!canToggle(doc)) {
    return `${base} cursor-not-allowed border-gray-100 bg-gray-50 opacity-75`;
  }
  if (isSelected(doc)) {
    return `${base} cursor-pointer border-primary ring-2 ring-primary ring-offset-1`;
  }
  return `${base} cursor-pointer border-gray-200 hover:border-primary/50`;
}
</script>

<template>
  <div class="grid grid-cols-2 gap-3 md:grid-cols-3">
    <Popover
      v-for="doc in normalizedDoctors"
      :key="doc.id"
      trigger="hover"
      placement="right"
    >
      <template #content>
        <Descriptions :column="1" size="small" class="max-w-[480px]">
          <DescriptionsItem label="ID">{{ doc.id }}</DescriptionsItem>
          <DescriptionsItem label="姓名">{{ doc.name }}</DescriptionsItem>
          <DescriptionsItem label="手机号">
            <SensitiveText :record="doc" field="mobile" />
          </DescriptionsItem>
          <DescriptionsItem label="身份证">
            <SensitiveText :record="doc" field="idcard" />
          </DescriptionsItem>
          <DescriptionsItem label="身份">{{ getDoctorTypeText(doc.type) }}</DescriptionsItem>
          <DescriptionsItem label="签名类型">
            {{ getSignTypeText(doc.sign_type) }}
          </DescriptionsItem>
          <DescriptionsItem label="科室">{{ doctorDepartName(doc) }}</DescriptionsItem>
          <DescriptionsItem label="职称">{{ doctorTitleName(doc) }}</DescriptionsItem>
          <DescriptionsItem label="擅长">{{ doc.good_at || '-' }}</DescriptionsItem>
          <DescriptionsItem label="简介">{{ doc.intro || '-' }}</DescriptionsItem>
          <DescriptionsItem label="审核状态">
            {{ getAuditStatusText(doc.status) }}
          </DescriptionsItem>
        </Descriptions>
        <div
          v-if="doctorCertImages(doc).length"
          class="mt-3 flex flex-wrap gap-2 border-t border-gray-100 pt-3"
        >
          <div
            v-for="(cert, idx) in doctorCertImages(doc)"
            :key="idx"
            class="text-center"
          >
            <Image
              :src="cert.url"
              :width="72"
              :height="72"
              :preview="true"
              class="rounded border border-gray-100"
            />
            <div class="mt-1 text-xs text-gray-500">{{ cert.label }}</div>
          </div>
        </div>
      </template>
      <div :class="cardClass(doc)" @click="toggleSelect(doc)">
        <div
          v-if="selectable && canToggle(doc) && isSelected(doc)"
          class="mb-1 text-right text-xs font-medium text-primary"
        >
          已选
        </div>
        <div
          v-else-if="selectable && onlyPendingSelectable && !isDoctorPending(doc)"
          class="mb-1 text-right text-xs text-gray-400"
        >
          {{ getAuditStatusText(doc.status) }}
        </div>
        <div class="mb-2 flex items-center gap-2">
          <Avatar
            v-if="resolveAvatarUrl(doc.avatar)"
            :src="resolveAvatarUrl(doc.avatar)"
            :size="40"
          />
          <Avatar v-else :size="40">{{ (doc.name || '?').charAt(0) }}</Avatar>
          <div class="min-w-0 flex-1">
            <div class="truncate font-medium">{{ doc.name || '-' }}</div>
            <div class="truncate text-xs text-gray-500">
              {{ doctorDepartName(doc) }} · {{ doctorTitleName(doc) }}
            </div>
          </div>
        </div>
        <div
          v-if="!selectable"
          class="text-xs"
          :class="{
            'text-orange-500': doc.status === 0,
            'text-green-500': doc.status === 1,
            'text-red-500': doc.status === 2,
          }"
        >
          {{ getAuditStatusText(doc.status) }}
        </div>
        <div
          v-if="doctorCertImages(doc).length"
          class="mt-2 flex flex-wrap gap-1"
        >
          <Image
            v-for="(cert, cidx) in doctorCertImages(doc).slice(0, 4)"
            :key="cidx"
            :src="cert.url"
            :width="48"
            :height="48"
            :preview="true"
            class="rounded border border-gray-100 object-cover"
          />
          <span
            v-if="doctorCertImages(doc).length > 4"
            class="flex h-12 w-12 items-center justify-center rounded bg-gray-50 text-xs text-gray-400"
          >
            +{{ doctorCertImages(doc).length - 4 }}
          </span>
        </div>
      </div>
    </Popover>
  </div>
</template>
