<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { h } from 'vue'
import { NButton, NCard, NDataTable, NEmpty, NInput, NModal, NSelect, NSpace, NTag, useMessage, useDialog } from 'naive-ui'
import { api } from '../../api/client'

const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const items = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(50)
const filterTargetNull = ref(false)
const filterAgency = ref<string | null>(null)

// Add modal
const showAdd = ref(false)
const addForm = ref({
  drug_name: '', generic_name: '', target: '', indication: '',
  approval_agency: 'NMPA', approval_type: 'new_drug',
  approval_date: '', source_url: '',
})
const agencyOptions = [
  { label: 'FDA', value: 'FDA' },
  { label: 'NMPA', value: 'NMPA' },
  { label: 'EMA', value: 'EMA' },
]
const typeOptions = [
  { label: '新药批准 (new_drug)', value: 'new_drug' },
  { label: '适应症扩展 (expanded_indication)', value: 'expanded_indication' },
]

async function load() {
  loading.value = true
  try {
    const params: any = { page: page.value, page_size: pageSize.value }
    if (filterTargetNull.value) params.target_null = true
    if (filterAgency.value) params.agency = filterAgency.value
    const r = await api.get('/admin/drug-approvals', { params })
    items.value = r.data.items
    total.value = r.data.total
  } catch (e: any) {
    message.error('加载失败: ' + (e.response?.data?.detail || e.message))
  } finally {
    loading.value = false
  }
}

async function updateTarget(row: any) {
  const newTarget = (row as any)._editTarget
  if (!newTarget || newTarget === row.target) return
  try {
    await api.put(`/admin/drug-approvals/${row.id}`, { target: newTarget })
    row.target = newTarget
    message.success('已更新')
  } catch (e: any) {
    message.error('更新失败: ' + (e.response?.data?.detail || e.message))
  }
}

function confirmDelete(row: any) {
  dialog.warning({
    title: '删除确认',
    content: `确定删除 ${row.drug_name} (${row.approval_date})？`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await api.delete(`/admin/drug-approvals/${row.id}`)
        message.success('已删除')
        load()
      } catch (e: any) {
        message.error('删除失败: ' + (e.response?.data?.detail || e.message))
      }
    },
  })
}

async function addRecord() {
  if (!addForm.value.drug_name || !addForm.value.approval_date) {
    message.warning('请填写药名和批准日期')
    return
  }
  try {
    await api.post('/admin/drug-approvals', addForm.value)
    message.success('已添加')
    showAdd.value = false
    addForm.value = { drug_name: '', generic_name: '', target: '', indication: '',
      approval_agency: 'NMPA', approval_type: 'new_drug', approval_date: '', source_url: '' }
    load()
  } catch (e: any) {
    message.error('添加失败: ' + (e.response?.data?.detail || e.message))
  }
}

const columns = computed(() => [
  { title: '药品名', key: 'drug_name', width: 130, ellipsis: { tooltip: true } },
  { title: '通用名', key: 'generic_name', width: 130, ellipsis: { tooltip: true } },
  {
    title: '靶点', key: 'target', width: 100,
    render: (row: any) => {
      if (row.target) {
        return h(NTag, { size: 'small', type: 'success' }, row.target)
      }
      return h('div', { style: 'display:flex;gap:4px;align-items:center' }, [
        h(NInput, {
          size: 'small', style: 'width:90px', placeholder: '填写靶点',
          value: row._editTarget,
          'onUpdate:value': (v: string) => row._editTarget = v,
        }),
        h(NButton, {
          size: 'tiny', type: 'primary', ghost: true,
          onClick: () => updateTarget(row),
        }, '✓'),
      ])
    },
  },
  {
    title: '类型', key: 'approval_type', width: 110,
    render: (row: any) => h(NTag, { size: 'small', type: row.approval_type === 'new_drug' ? 'info' : 'warning' },
      row.approval_type === 'new_drug' ? '新药' : '扩展'),
  },
  { title: '日期', key: 'approval_date', width: 100 },
  { title: '机构', key: 'approval_agency', width: 60 },
  {
    title: '操作', key: 'actions', width: 70,
    render: (row: any) => h(NButton, { size: 'tiny', type: 'error', ghost: true, onClick: () => confirmDelete(row) }, '删除'),
  },
])
const scrollX = computed(() => columns.value.reduce((s: number, c: any) => s + (c.width || c.minWidth || 200), 0))

onMounted(load)
</script>

<template>
  <NCard title="💊 药品审批管理">
    <template #header-extra>
      <NSpace>
        <NSelect v-model:value="filterAgency" :options="agencyOptions" placeholder="全部机构" clearable style="width:120px" @update:value="load" />
        <NButton :type="filterTargetNull ? 'warning' : 'default'" size="small" @click="filterTargetNull = !filterTargetNull; load()">
          {{ filterTargetNull ? '📌 显示全部' : '🎯 仅缺靶点' }}
        </NButton>
        <NButton type="primary" size="small" @click="showAdd = true">+ 手动添加</NButton>
        <NButton size="small" @click="load">刷新</NButton>
      </NSpace>
    </template>

    <NDataTable
      :columns="columns"
      :data="items"
      :loading="loading"
      :bordered="false"
      :single-line="false"
      :max-height="600"
      :scroll-x="scrollX"
      size="small"
      style="margin-top:8px"
    />
    <div v-if="!loading && items.length === 0" style="padding:40px">
      <NEmpty description="暂无记录" />
    </div>
    <div v-if="total > pageSize" style="display:flex;justify-content:center;padding:16px">
      <NButton size="small" :disabled="page <= 1" @click="page--; load()">上一页</NButton>
      <span style="padding:0 12px;line-height:28px">{{ page }} / {{ Math.ceil(total / pageSize) }}</span>
      <NButton size="small" :disabled="page * pageSize >= total" @click="page++; load()">下一页</NButton>
    </div>
    <div style="color:var(--text-color-3);font-size:12px;padding:8px 0 0">
      共 {{ total }} 条 | 点击 🎯 筛选靶点缺失的记录 → 填写靶点 → 按 ✓ 保存 | 手动添加用于 NMPA 等非 FDA 数据
    </div>
  </NCard>

  <!-- Add Modal -->
  <NModal v-model:show="showAdd" title="手动添加审批记录" preset="card" style="width:500px">
    <div style="display:flex;flex-direction:column;gap:10px">
      <NInput v-model:value="addForm.drug_name" placeholder="药品名 *（必填）" />
      <NInput v-model:value="addForm.generic_name" placeholder="通用名" />
      <NInput v-model:value="addForm.target" placeholder="靶点（如 EGFR, PD-1）" />
      <NInput v-model:value="addForm.indication" placeholder="适应症" />
      <NSelect v-model:value="addForm.approval_agency" :options="agencyOptions" />
      <NSelect v-model:value="addForm.approval_type" :options="typeOptions" />
      <NInput v-model:value="addForm.approval_date" placeholder="批准日期 * YYYY-MM-DD" />
      <NInput v-model:value="addForm.source_url" placeholder="来源链接" />
      <NSpace justify="end" style="margin-top:8px">
        <NButton @click="showAdd = false">取消</NButton>
        <NButton type="primary" @click="addRecord">添加</NButton>
      </NSpace>
    </div>
  </NModal>
</template>
