<template>
  <div class="art-page-view">
    <MerchantSearch v-model="formFilters" @search="handleSearch" @reset="handleReset" />

    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columns"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      />

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
      >
        <template #status="{ row }">
          <ElTag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</ElTag>
        </template>
        <template #operatingMode="{ row }">
          <span>{{ getOperatingModeText(row.operatingMode) }}</span>
        </template>
        <template #frozen="{ row }">
          <ElTag :type="row.isFrozen ? 'danger' : 'success'">
            {{ row.isFrozen ? t('merchant.frozen.yes') : t('merchant.frozen.no') }}
          </ElTag>
        </template>
        <template #storeCount="{ row }">
          <span>{{ row.storeCount ?? 0 }}</span>
        </template>
        <template #action="{ row }">
          <div class="action-wrap">
            <button class="art-action-btn" @click="handleDetail(row)">
              <ArtSvgIcon icon="ri:information-line" class="art-action-icon" />
              <span>{{ t('dictionary.common.detail') }}</span>
            </button>
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <ElDrawer
      v-model="detailDrawerVisible"
      size="50%"
      :with-header="false"
      destroy-on-close
      @closed="currentMerchantId = undefined"
    >
      <MerchantDetail :merchant-id="currentMerchantId" />
    </ElDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElCard, ElDrawer, ElTag } from 'element-plus'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtTableHeader from '@/components/core/tables/art-table-header/index.vue'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import { useTable } from '@/hooks/core/useTable'
  import { fetchMerchantList } from '@/api/merchant'
  import { MerchantStatus } from '@/enums/MerchantStatus'
  import { OperatingMode } from '@/enums/OperatingMode'
  import { formatDateTime } from '@/utils/billing'
  import MerchantSearch from './modules/merchant-search.vue'
  import MerchantDetail from '../detail/index.vue'
  import type { ColumnOption } from '@/types/component'
  import type { MerchantListSearchForm } from './types'

  defineOptions({ name: 'MerchantList' })

  const { t } = useI18n()
  const showSearchBar = ref(true)
  const detailDrawerVisible = ref(false)
  const currentMerchantId = ref<string>()

  const formFilters = ref<MerchantListSearchForm>({
    keyword: '',
    status: undefined,
    operatingMode: undefined,
    tenantId: ''
  })

  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof fetchMerchantList, Api.Merchant.MerchantListItem>({
    core: {
      apiFn: fetchMerchantList,
      apiParams: {
        Page: 1,
        PageSize: 20
      },
      paginationKey: {
        current: 'Page',
        size: 'PageSize'
      },
      columnsFactory: (): ColumnOption<Api.Merchant.MerchantListItem>[] => [
        { type: 'globalIndex', label: '#', width: 60, fixed: 'left' },
        { prop: 'name', label: t('merchant.list.table.name'), minWidth: 180 },
        { prop: 'tenantName', label: t('merchant.list.table.tenantName'), minWidth: 160 },
        {
          prop: 'operatingMode',
          label: t('merchant.list.table.operatingMode'),
          width: 140,
          useSlot: true
        },
        { prop: 'status', label: t('merchant.list.table.status'), width: 120, useSlot: true },
        { prop: 'frozen', label: t('merchant.list.table.frozen'), width: 120, useSlot: true },
        {
          prop: 'storeCount',
          label: t('merchant.list.table.storeCount'),
          width: 120,
          useSlot: true
        },
        {
          prop: 'createdAt',
          label: t('merchant.list.table.createdAt'),
          width: 180,
          formatter: (row) => formatDateTime(row.createdAt)
        },
        { prop: 'action', label: t('common.action'), width: 140, fixed: 'right', useSlot: true }
      ]
    }
  })

  const handleSearch = (params: MerchantListSearchForm) => {
    searchParams.keyword = params.keyword || undefined
    searchParams.status = params.status
    searchParams.operatingMode = params.operatingMode
    searchParams.tenantId = params.tenantId ? params.tenantId.trim() : undefined
    refreshData()
  }

  const handleReset = () => {
    formFilters.value = { keyword: '', status: undefined, operatingMode: undefined, tenantId: '' }
    searchParams.keyword = undefined
    searchParams.status = undefined
    searchParams.operatingMode = undefined
    searchParams.tenantId = undefined
    refreshData()
  }

  const handleDetail = (row: Api.Merchant.MerchantListItem) => {
    currentMerchantId.value = String(row.id)
    detailDrawerVisible.value = true
  }

  const getStatusType = (status: number) => {
    switch (status) {
      case MerchantStatus.Pending:
        return 'warning'
      case MerchantStatus.Approved:
        return 'success'
      case MerchantStatus.Rejected:
        return 'danger'
      case MerchantStatus.Frozen:
        return 'info'
      default:
        return 'info'
    }
  }

  const getStatusText = (status: number) => {
    switch (status) {
      case MerchantStatus.Pending:
        return t('merchant.status.pending')
      case MerchantStatus.Approved:
        return t('merchant.status.approved')
      case MerchantStatus.Rejected:
        return t('merchant.status.rejected')
      case MerchantStatus.Frozen:
        return t('merchant.status.frozen')
      default:
        return t('merchant.status.unknown')
    }
  }

  const getOperatingModeText = (mode?: number) => {
    switch (mode) {
      case OperatingMode.SameEntity:
        return t('merchant.operatingMode.same')
      case OperatingMode.DifferentEntity:
        return t('merchant.operatingMode.different')
      default:
        return '-'
    }
  }
</script>
