import { useEffect, useMemo, useRef, useState } from 'react'
import { useSearchParams } from '@/router/hooks'
import imgQR from '@/assets/images/qrcode/wechat_qrcode.png'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { toast } from 'sonner'
import { openDeclForm } from '@/api/services/riskcontrol/declare'
import { DeclState, DeclStateText } from '@/api/services/riskcontrol/enum'
import { Button, Divider, Input, Layout, Result } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import FormParse, { type FormParseRef } from '@/components/formParse'

const { Search } = Input

type IPageState = 'secretInput' | 'missParams' | 'decl' | 'loading' | 'success'

const maskWrapperClass = 'absolute top-0 left-0 w-full h-full'
const maskDialogWrapperClass =
  'w-[300px] h-[160px] bg-[white] absolute-content-center rounded-[4px] box-border px-[24px] py-[24px]'

function Decl() {
  const [pageState, setPageState] = useState<IPageState>('success')
  const [orderState, setOrderState] = useState('')
  console.log(orderState)
  const [declFormData, setDeclFormData] = useState<API.OpenDeclFormResult>()
  const [imgOSS] = useState('')

  const FormParseRef = useRef<FormParseRef>(null)

  // 问卷是否过期
  const isExpiry = useMemo(() => {
    const expiryDate = declFormData?.expiryDate
    const isExpiryVal = expiryDate && dayjs(expiryDate).isBefore(dayjs().format('YYYY-MM-DD'))
    return !!isExpiryVal
  }, [])

  const searchParams = useSearchParams()
  const tId = searchParams.get('tId') || ''
  const declSn = searchParams.get('declSn') || ''
  const secretKey = searchParams.get('secretKey') || ''

  const [formData, setFormData] = useState<Record<string, any>>({})
  const [formRule, setFormRule] = useState({})
  type ISubmitType = 'save' | 'submit' | 'onlySave' | 'autoSave'
  const [resultType] = useState<Nullable<ISubmitType>>(null)

  const [btnLoading, setBtnLoading] = useState(false)
  const confirmSecretFn = async () => {
    setFormData({})
    setFormRule({})
    setBtnLoading(true)
    const res = await openDeclForm({
      tId,
      declSn,
      secretKey
    })
    setBtnLoading(false)
    if (res?.code === '2000') {
      setDeclFormData(res.data)
      setPageState('decl')
      setOrderState(declFormData?.payDetail?.orderState as string)
    }
  }
  useEffect(() => {
    if (!tId || !declSn) {
      setPageState('missParams')
      toast.warning('链接缺少关键参数', { position: 'top-center' })
    } else if (secretKey) {
      confirmSecretFn()
    } else {
      setPageState('secretInput')
    }
  }, [])

  const [isAutoSaveing] = useState(false)

  // 配置保存数据的格式
  const submitFn = async (type: ISubmitType, isAfterPayment = false) => {
    console.log(type)
    console.log(isAfterPayment)
  }

  return (
    <Layout>
      <div className='decl-page relative !h-screen bg-gradient-to-b from-[#F2F7FE] to-[#FAFBFC]'>
        {pageState === 'loading' && (
          <div className='loading-mask absolute-content-center text-primary text-[20px]'>
            <LoadingOutlined />
            <span className='ml-[12px]'>内容加载中...</span>
          </div>
        )}

        {pageState === 'secretInput' && (
          <div className={classNames('bg-[black] bg-opacity-50', maskWrapperClass)}>
            <div className={classNames(maskDialogWrapperClass)}>
              <div className='mb-[20px] font-[500] text-[16px]'>打开申报单</div>
              <Search
                placeholder='请输入提取码'
                allowClear
                onSearch={confirmSecretFn}
                style={{ width: '100%' }}
              />
            </div>
          </div>
        )}

        {pageState === 'missParams' && (
          <div className={classNames('bg-#f5f7fa', maskWrapperClass)}>
            <div className={classNames(maskDialogWrapperClass)}>
              <h2>缺少关键参数</h2>
              <span className='text-text-secondary'>请检查您的链接是否正确</span>
            </div>
          </div>
        )}

        {pageState === 'decl' && (
          <div className='decl-form-wrapper h-full py-[80px] box-border'>
            <div className='decl-content mx-auto w-[880px]'>
              <div className='px-[30px] py-[40px] rounded-[8px] bg-[white]'>
                <div className='text-[20px] text-center font-500'>
                  {`“${declFormData?.enterpriseName}”，请填写申报`}
                </div>
                <Divider />
                {declFormData?.formItems && (
                  <FormParse
                    ref={FormParseRef}
                    formData={formData}
                    onFormDataChange={setFormData}
                    formRule={formRule}
                    onFormRuleChange={setFormRule}
                    declFormData={declFormData}
                    state={DeclStateText[declFormData.declarationState!]}
                    expiry={declFormData?.expiryDate}
                    isExpiry={isExpiry}
                    disabled={
                      declFormData?.declarationState === DeclState.SUBMITTED ||
                      declFormData?.declarationState === DeclState.CHECKED ||
                      isExpiry
                    }
                    className='mt-10'
                  />
                )}
                <div className='fixed right-[10px] top-[50%] -translate-y-[50%]'>
                  <img className='w-[300px]' src={imgOSS || imgQR} alt='' />
                </div>
              </div>
            </div>
          </div>
        )}

        {pageState === 'success' && (
          <div className={classNames('bg-#f5f7fa', maskWrapperClass)}>
            <div className={classNames('!h-[330px]', maskDialogWrapperClass)}>
              <Result
                status='success'
                title={resultType === 'save' ? '保存成功' : '申报成功'}
                subTitle={`“${declFormData?.enterpriseName}”邀请您填写的申报已${
                  resultType === 'save' ? '保存，未提交申报' : '成功'
                }`}
                extra={
                  <Button type='primary' loading={btnLoading} onClick={confirmSecretFn}>
                    返回查看
                  </Button>
                }
              />
            </div>
          </div>
        )}

        {(declFormData?.declarationState === DeclState.UNREAD ||
          declFormData?.declarationState === DeclState.READ ||
          declFormData?.declarationState === DeclState.ROLLBACK) &&
          !isExpiry &&
          pageState !== 'success' && (
            <div
              className='fixed bottom-0 left-0 w-full bg-[white] h-[64px]'
              style={{ boxShadow: '0px -1px 2px 0px rgba(0, 0, 0, 0.06)' }}>
              <div className='w-[880px] mx-auto flex items-center justify-end h-full'>
                <span className='text-[12px] text-[#F54A45] mr-[16px]'>
                  填写过程中请及时保存，避免页面关闭后信息丢失
                </span>
                {isAutoSaveing && (
                  <span className='text-[12px] text-[primary] mr-[16px]'>自动保存中...</span>
                )}
                <Button loading={btnLoading} onClick={() => submitFn('save')}>
                  保 存
                </Button>
                <Button
                  loading={btnLoading}
                  type='primary'
                  className='ml-[8px] mr-[30px]'
                  onClick={() => submitFn('submit')}>
                  提 交
                </Button>
              </div>
            </div>
          )}
      </div>
    </Layout>
  )
}

export default Decl
