import { useEffect, useMemo, useState } from 'react'
import { BetaSchemaForm, ProColumns, ProFormColumnsType, ProTable } from '@ant-design/pro-components'
import { useTranslation } from '@/i18n.ts'
import { useAtom, useAtomValue } from 'jotai'
import { Button, Form, Popconfirm } from 'antd'
import {
  deleteDNSAtom,
  dnsListAtom,
  dnsPageAtom,
  DNSTypeEnum,
  DNSTypes,
  saveOrUpdateDNSAtom
} from '@/store/websites/dns.ts'
import { WebSite } from '@/types'

const getKeyColumn = (type: string, t) => {
  const columns: ProColumns<WebSite.IDnsAccount>[] = []
  switch (type) {
    case DNSTypeEnum.AliYun: {
      columns.push(...[
        {
          title: t('website.ssl.dns.columns.accessKey', 'Access Key'),
          dataIndex: 'accessKey',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        },
        {
          title: t('website.ssl.dns.columns.secretKey', 'Secret Key'),
          dataIndex: 'secretKey',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        },
      ])
    }
      break
    case  DNSTypeEnum.TencentCloud: {
      columns.push(...[
        {
          title: t('website.ssl.dns.columns.secretID', 'Secret ID'),
          dataIndex: 'secretID',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        }, {
          title: t('website.ssl.dns.columns.secretKey', 'Secret Key'),
          dataIndex: 'secretKey',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        },
      ])
      break
    }
    case DNSTypeEnum.DnsPod: {
      columns.push(...[
        {
          title: t('website.ssl.dns.columns.apiId', 'ID'),
          dataIndex: 'apiId',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        }, {
          title: t('website.ssl.dns.columns.token', 'Token'),
          dataIndex: 'token',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        },
      ])
      break
    }
    case DNSTypeEnum.CloudFlare: {
      columns.push(...[
          {
            title: t('website.ssl.dns.columns.email', 'Email'),
            dataIndex: 'email',
            formItemProps: {
              rules: [ { required: true, message: t('message.required') } ]
            }
          }, {
            title: t('website.ssl.dns.columns.apiKey', 'API ToKen'),
            dataIndex: 'apiKey',
            formItemProps: {
              rules: [ { required: true, message: t('message.required') } ]
            }
          },
        ]
      )
      break
    }
    case DNSTypeEnum.Godaddy:
    case DNSTypeEnum.NameCheap:
    case DNSTypeEnum.NameSilo:
      columns.push({
          title: t('website.ssl.dns.columns.apiKey', 'API Key'),
          dataIndex: 'apiKey',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        },
      )
      if (type === DNSTypeEnum.NameCheap) {
        columns.push({
          title: t('website.ssl.dns.columns.apiUser', 'API User'),
          dataIndex: 'apiUser',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        })
      } else if (type === DNSTypeEnum.Godaddy) {
        columns.push({
          title: t('website.ssl.dns.columns.apiSecret', 'API Secret'),
          dataIndex: 'apiSecret',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        })
      }
      break
    case DNSTypeEnum.NameCom: {
      columns.push(
        {
          title: t('website.ssl.dns.columns.apiUser', 'UserName'),
          dataIndex: 'apiUser',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        },
        {
          title: t('website.ssl.dns.columns.token', 'Token'),
          dataIndex: 'token',
          formItemProps: {
            rules: [ { required: true, message: t('message.required') } ]
          }
        }
      )
      break
    }
    default:
      break

  }
  return columns
}

const DNSList = () => {

  const { t } = useTranslation()
  const [ form ] = Form.useForm()
  const [ page, setPage ] = useAtom(dnsPageAtom)
  const { data, isLoading, isFetching, refetch } = useAtomValue(dnsListAtom)
  const { mutate: saveOrUpdate, isPending: isSubmitting, isSuccess } = useAtomValue(saveOrUpdateDNSAtom)
  const { mutate: deleteDNS, isPending: isDeleting } = useAtomValue(deleteDNSAtom)
  const [ open, setOpen ] = useState(false)

  const columns = useMemo<ProColumns<WebSite.IDnsAccount>[]>(() => {
    return [
      {
        title: 'ID',
        dataIndex: 'id',
        hideInTable: true,
        formItemProps: {
          hidden: true,
        }
      },
      {
        title: t('website.ssl.dns.columns.name', '名称'),
        dataIndex: 'name',
        valueType: 'text',
        formItemProps: {
          rules: [
            { required: true, message: t('message.required', '请输入') }
          ]
        }
      },

      {
        title: t('website.ssl.dns.columns.type', '类型'),
        dataIndex: 'type',
        valueType: 'select',
        fieldProps: {
          options: DNSTypes
        },
        formItemProps: {
          rules: [
            { required: true, message: t('message.required', '请选择') }
          ]
        },
      },
      {
        name: [ 'type' ],
        valueType: 'dependency',
        hideInSetting: true,
        hideInTable: true,
        columns: ({ type }) => {
          return getKeyColumn(type, t)
        }
      },
      {
        title: '操作',
        valueType: 'option',
        render: (_, record) => {
          return [
            <Popconfirm
              key={'del_confirm'}
              disabled={isDeleting}
              onConfirm={() => {
                deleteDNS(record.id)
              }}
              title={t('message.deleteConfirm')}>
              <a key="del">
                {t('actions.delete', '删除')}
              </a>
            </Popconfirm>
          ]
        }
      }
    ]
  }, [])

  useEffect(() => {
    if (isSuccess) {
      setOpen(false)
    }
  }, [ isSuccess ])

  return (
    <>
      <ProTable<WebSite.IDnsAccount>
        cardProps={{
          bodyStyle: {
            padding: 0,
          }
        }}
        rowKey="id"
        headerTitle={
          <Button
            onClick={() => {
              form.setFieldsValue({
                id: 0,
                type: DNSTypeEnum.DnsPod,
              })
              setOpen(true)
            }}
            type={'primary'}>{t('website.ssl.dns.add', '添加DNS帐户')}</Button>
        }
        loading={isLoading || isFetching}
        dataSource={data?.rows ?? []}
        columns={columns}
        search={false}
        options={{
          reload: () => {
            refetch()
          },
        }}
        pagination={{
          total: data?.total,
          pageSize: page.pageSize,
          current: page.page,
          onChange: (current, pageSize) => {
            setPage(prev => {
              return {
                ...prev,
                page: current,
                pageSize: pageSize,
              }
            })
          },

        }}
      />
      <BetaSchemaForm<WebSite.IDnsAccount>
        shouldUpdate={false}
        width={600}
        form={form}
        layout={'horizontal'}
        scrollToFirstError={true}
        title={t(`website.ssl.dns.title_${form.getFieldValue('id') !== 0 ? 'edit' : 'add'}`, form.getFieldValue('id') !== 0 ? 'DNS帐号编辑' : 'DNS帐号添加')}
        // colProps={{ span: 24 }}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        layoutType={'ModalForm'}
        open={open}
        modalProps={{
          maskClosable: false,
        }}
        onOpenChange={(open) => {
          setOpen(open)
        }}
        loading={isSubmitting}
        onFinish={async (values) => {
          // console.log('values', values)
          saveOrUpdate(values)
        }}
        columns={columns as ProFormColumnsType[]}/>
    </>
  )
}

export default DNSList