<template>
  <div class="ip-list-tab">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="IP地址列表"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增IP
        </a-button>
      </template>

      <template #allocation_status="{ record }">
        <a-tag :color="getAllocationStatusColor(record.allocation_status)" bordered>
          {{ getAllocationStatusText(record.allocation_status) }}
        </a-tag>
      </template>

      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)" bordered>
          {{ getStatusText(record.status) }}
        </a-tag>
      </template>

      <template #usage_status="{ record }">
        <a-tag :color="getUsageStatusColor(record.usage_status)" bordered>
          {{ getUsageStatusText(record.usage_status) }}
        </a-tag>
      </template>

      <template #source_type="{ record }">
        <a-tag :color="getSourceTypeColor(record.source_type)" bordered>
          {{ getSourceTypeText(record.source_type) }}
        </a-tag>
      </template>

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

      <template #actions="{ record }">
        <a-space>
          <a-button type="text" size="small" @click="handleEdit(record)">编辑</a-button>
          <a-popconfirm content="确定删除该IP地址吗？" @ok="handleDelete(record)">
            <a-button type="text" size="small" status="danger">删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </search-table>

    <IPFormDialog v-model="showFormDialog" :edit-data="currentEditData" :subnets="subnets" @success="handleFormSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import SearchTable from '@/components/search-table/index.vue'
import IPFormDialog from './IPFormDialog.vue'
import { ipAllocationColumns } from '../config/columns'
import {
  fetchIPAddressList,
  deleteIPAddress,
  fetchIPSubnetList,
  type IPAddressItem,
  type IPAddressListParams,
  type IPSubnetItem,
  type AllocationStatus,
  type IPStatus,
  type UsageStatus,
  type SourceType,
} from '@/api/ops/ipam'
import type { FormItem } from '@/components/search-form/types'

const loading = ref(false)
const tableData = ref<IPAddressItem[]>([])
const subnets = ref<IPSubnetItem[]>([])
const showFormDialog = ref(false)
const currentEditData = ref<IPAddressItem | null>(null)

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

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

const formItems = computed<FormItem[]>(() => [
  {
    field: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入IP地址、主机名',
    span: 6,
  },
  {
    field: 'subnet_id',
    label: '子网',
    type: 'select',
    placeholder: '全部子网',
    options: subnets.value.map((s) => ({ label: `${s.name} (${s.cidr})`, value: s.id })),
    span: 6,
  },
  {
    field: 'allocation_status',
    label: '分配状态',
    type: 'select',
    placeholder: '全部状态',
    options: [
      { label: '已分配', value: 'allocated' },
      { label: '未分配', value: 'unallocated' },
      { label: '保留', value: 'reserved' },
    ],
    span: 6,
  },
  {
    field: 'status',
    label: '运行状态',
    type: 'select',
    placeholder: '全部状态',
    options: [
      { label: '在线', value: 'online' },
      { label: '离线', value: 'offline' },
      { label: '未知', value: 'unknown' },
    ],
    span: 6,
  },
  {
    field: 'usage_status',
    label: '使用状态',
    type: 'select',
    placeholder: '全部状态',
    options: [
      { label: '已使用', value: 'used' },
      { label: '未使用', value: 'unused' },
      { label: '30天内使用', value: 'used_within_30d' },
      { label: '30天前使用', value: 'used_before_30d' },
    ],
    span: 6,
  },
])

const columns = ipAllocationColumns

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: IPAddressListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formModel,
    }

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

    const response = await fetchIPAddressList(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 IP addresses:', 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: '',
    allocation_status: '',
    status: '',
    usage_status: '',
  })
  pagination.current = 1
  loadData()
}

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

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

const handleAdd = () => {
  currentEditData.value = null
  showFormDialog.value = true
}

const handleEdit = (record: IPAddressItem) => {
  currentEditData.value = record
  showFormDialog.value = true
}

const handleDelete = async (record: IPAddressItem) => {
  try {
    await deleteIPAddress(record.id)
    Message.success('删除成功')
    loadData()
  } catch (error) {
    Message.error('删除失败')
  }
}

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

const getAllocationStatusColor = (status: AllocationStatus) => {
  const colorMap: Record<AllocationStatus, string> = {
    allocated: 'blue',
    unallocated: 'gray',
    reserved: 'orange',
  }
  return colorMap[status] || 'gray'
}

const getAllocationStatusText = (status: AllocationStatus) => {
  const textMap: Record<AllocationStatus, string> = {
    allocated: '已分配',
    unallocated: '未分配',
    reserved: '保留',
  }
  return textMap[status] || status
}

const getStatusColor = (status: IPStatus) => {
  const colorMap: Record<IPStatus, string> = {
    online: 'green',
    offline: 'red',
    unknown: 'gray',
  }
  return colorMap[status] || 'gray'
}

const getStatusText = (status: IPStatus) => {
  const textMap: Record<IPStatus, string> = {
    online: '在线',
    offline: '离线',
    unknown: '未知',
  }
  return textMap[status] || status
}

const getUsageStatusColor = (status: UsageStatus) => {
  const colorMap: Record<UsageStatus, string> = {
    used: 'green',
    unused: 'gray',
    used_within_30d: 'blue',
    used_before_30d: 'orange',
  }
  return colorMap[status] || 'gray'
}

const getUsageStatusText = (status: UsageStatus) => {
  const textMap: Record<UsageStatus, string> = {
    used: '已使用',
    unused: '未使用',
    used_within_30d: '30天内使用',
    used_before_30d: '30天前使用',
  }
  return textMap[status] || status
}

const getSourceTypeColor = (type: SourceType) => {
  const colorMap: Record<SourceType, string> = {
    scan: 'cyan',
    dhcp: 'purple',
    manual: 'arcoblue',
  }
  return colorMap[type] || 'gray'
}

const getSourceTypeText = (type: SourceType) => {
  const textMap: Record<SourceType, string> = {
    scan: '扫描',
    dhcp: 'DHCP',
    manual: '手工',
  }
  return textMap[type] || type
}

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

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