<template>
  <div class="dhcp-leases-tab">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="DHCP租约"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #status="{ record }">
        <a-tag :color="record.status === 'active' ? 'green' : 'gray'" bordered>
          {{ record.status === 'active' ? '活跃' : '已过期' }}
        </a-tag>
      </template>

      <template #lease_start="{ record }">
        {{ formatDateTime(record.lease_start) }}
      </template>

      <template #lease_end="{ record }">
        {{ formatDateTime(record.lease_end) }}
      </template>

      <template #actions="{ record }">
        <a-button type="text" size="small" @click="handleDetail(record)">详情</a-button>
      </template>
    </search-table>

    <a-modal v-model:visible="showDetailDialog" title="租约详情" :width="600" :footer="false">
      <a-descriptions :data="detailData" :column="2" bordered />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import SearchTable from '@/components/search-table/index.vue'
import { fetchDHCPLeaseList, fetchIPSubnetList, type DHCPLeaseItem, type DHCPLeaseListParams, type IPSubnetItem } from '@/api/ops/ipam'
import type { FormItem } from '@/components/search-form/types'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'

const loading = ref(false)
const tableData = ref<DHCPLeaseItem[]>([])
const subnets = ref<IPSubnetItem[]>([])
const showDetailDialog = ref(false)
const currentDetail = ref<DHCPLeaseItem | null>(null)

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

const formModel = reactive({
  keyword: '',
  subnet_id: '',
})

const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入IP地址、MAC地址',
    span: 8,
  },
  {
    field: 'subnet_id',
    label: '子网',
    type: 'select',
    placeholder: '全部子网',
    options: subnets.value.map((s) => ({ label: `${s.name} (${s.cidr})`, value: s.id })),
    span: 8,
  },
])

const columns: TableColumnData[] = [
  { title: 'IP地址', dataIndex: 'ip_address', width: 150 },
  { title: 'MAC地址', dataIndex: 'mac_address', width: 180 },
  { title: '主机名', dataIndex: 'hostname', width: 200 },
  { title: '所属子网', dataIndex: 'subnet_name', width: 150 },
  { title: 'DHCP服务器', dataIndex: 'dhcp_server', width: 150 },
  { title: '租约开始', dataIndex: 'lease_start', slotName: 'lease_start', width: 180 },
  { title: '租约结束', dataIndex: 'lease_end', slotName: 'lease_end', width: 180 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 100, align: 'center' },
  { title: '操作', dataIndex: 'actions', slotName: 'actions', width: 100, fixed: 'right' },
]

const detailData = computed(() => {
  if (!currentDetail.value) return []
  return [
    { label: 'IP地址', value: currentDetail.value.ip_address },
    { label: 'MAC地址', value: currentDetail.value.mac_address },
    { label: '主机名', value: currentDetail.value.hostname },
    { label: '所属子网', value: currentDetail.value.subnet_name },
    { label: 'DHCP服务器', value: currentDetail.value.dhcp_server },
    { label: '租约开始', value: formatDateTime(currentDetail.value.lease_start) },
    { label: '租约结束', value: formatDateTime(currentDetail.value.lease_end) },
    { label: '状态', value: currentDetail.value.status === 'active' ? '活跃' : '已过期' },
  ]
})

const loadSubnets = async () => {
  try {
    const response = await fetchIPSubnetList({ size: 1000 })
    if (response && response.code === 0) {
      subnets.value = response.details?.data || response.data || []
    }
  } catch (error) {
    console.error('Failed to load subnets:', error)
  }
}

const loadData = async () => {
  loading.value = true
  try {
    const params: DHCPLeaseListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formModel,
    }

    Object.keys(params).forEach((key) => {
      if (!params[key as keyof DHCPLeaseListParams]) {
        delete params[key as keyof DHCPLeaseListParams]
      }
    })

    const response = await fetchDHCPLeaseList(params)
    if (response && response.code === 0) {
      tableData.value = response.details?.data || response.data || []
      pagination.total = response.details?.total || response.total || 0
    }
  } catch (error) {
    console.error('Failed to load DHCP leases:', error)
  } finally {
    loading.value = false
  }
}

const handleFormModelUpdate = (model: typeof formModel) => {
  Object.assign(formModel, model)
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(formModel, {
    keyword: '',
    subnet_id: '',
  })
  pagination.current = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  loadData()
}

const handleRefresh = () => {
  loadData()
}

const handleDetail = (record: DHCPLeaseItem) => {
  currentDetail.value = record
  showDetailDialog.value = true
}

const formatDateTime = (datetime: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

onMounted(() => {
  loadSubnets()
  loadData()
})
</script>
