import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import useUserStore from '@/store/userStore'
import { useLoginByUsername } from '@/store/userStore'
import { DEFAULT_USER } from '@/_mock/assets'
import { toast } from 'sonner'
import { getTenantByName } from '@/api/services/login'
import { Button, Checkbox, Col, Divider, Form, Input, Row } from 'antd'
import PrivacyPolicyModal, { type PrivacyPolicyDialogProps } from './components/PrivacyPolicyModal'
import UserAgreementModal, { type UserAgreementModalProps } from './components/UserAgreementModal'
import Verify, { type VerifyRef } from '@/components/verifition/Verify'
// import { LoginStateEnum, useLoginStateContext } from './providers/LoginStateProvider'
import { VerifyProvider } from './providers/VerifyProvider'

export interface ILoginForm {
  username: string
  password: string
  tenant_id?: number
  tenant_name?: string
  code: string
  randomStr: string
}

function LoginForm() {
  const { t } = useTranslation()
  const [loading, setLoading] = useState(false)

  // const { loginState, setLoginState } = useLoginStateContext()
  // const signIn = useSignIn();
  const loginFn = useLoginByUsername()

  // if (loginState !== LoginStateEnum.LOGIN) return null
  const { actions } = useUserStore()
  const loginForm = useRef<ILoginForm>({
    username: '',
    password: '',
    tenant_id: undefined,
    tenant_name: '',
    code: '',
    randomStr: 'blockPuzzle'
  })
  const handleFinish = async (values: ILoginForm) => {
    if (values.tenant_name) {
      setLoading(true)
      loginForm.current.username = values.username
      loginForm.current.password = values.password
      getTenantByName({ identifier: values.tenant_name! }).then((res) => {
        setLoading(false)
        if (!res?.data?.tenantId) {
          toast.warning('未查询到租户！', { position: 'top-center' })
        } else {
          loginForm.current.tenant_id = res.data.tenantId
          actions.setTenantId(loginForm.current.tenant_id)
          // 显示滑动验证码
          verifyRef.current?.show()
        }
      })
    } else {
      toast.warning('请输入租户！', { position: 'top-center' })
    }
  }
  // 滑块验证
  const verifyRef = useRef<VerifyRef>(null)
  const verifySuccess = function (params: { captchaVerification: string }) {
    loginForm.current.code = params.captchaVerification
    const submitData = { ...loginForm.current }
    delete submitData.tenant_name
    loginFn(submitData)
  }

  const [userAgreementModalProps, setUserAgreementModalProps] = useState<UserAgreementModalProps>({
    title: '用户协议',
    show: false,
    onCancel: () => {
      setUserAgreementModalProps((prev) => ({ ...prev, show: false }))
    }
  })
  const [privacyPolicyModalProps, setPrivacyPolicyModalProps] = useState<PrivacyPolicyDialogProps>({
    title: '隐私权政策',
    show: false,
    onCancel: () => {
      setPrivacyPolicyModalProps((prev) => ({ ...prev, show: false }))
    }
  })
  const viewAgreement = (agreementName: string) => {
    if (agreementName === 'userAgreement') {
      setUserAgreementModalProps((prev) => ({ ...prev, show: true }))
    }
    if (agreementName === 'privacyPolicy') {
      setPrivacyPolicyModalProps((prev) => ({ ...prev, show: true }))
    }
  }
  return (
    <>
      <div className='mb-4 text-2xl font-bold xl:text-3xl'>{t('sys.login.signInFormTitle')}</div>
      <Form
        name='login'
        size='large'
        initialValues={{
          remember: true,
          tenant_name: DEFAULT_USER.tenant_name,
          username: DEFAULT_USER.username,
          password: DEFAULT_USER.password
        }}
        onFinish={handleFinish}>
        <Form.Item
          name='tenant_name'
          rules={[{ required: true, message: t('sys.login.tenantNamePlaceholder') }]}>
          <Input placeholder={t('sys.login.tenantName')} />
        </Form.Item>
        <Form.Item
          name='username'
          rules={[{ required: true, message: t('sys.login.accountPlaceholder') }]}>
          <Input placeholder={t('sys.login.userName')} />
        </Form.Item>
        <Form.Item
          name='password'
          rules={[{ required: true, message: t('sys.login.passwordPlaceholder') }]}>
          <Input.Password type='password' placeholder={t('sys.login.password')} />
        </Form.Item>
        <Form.Item>
          <Row align='middle'>
            <Col span={12}>
              <Form.Item name='remember' valuePropName='checked' noStyle>
                <Checkbox>{t('sys.login.rememberMe')}</Checkbox>
              </Form.Item>
            </Col>
            {/* <Col span={12} className="text-right">
							<Button
								type="link"
								className="!underline"
								onClick={() => setLoginState(LoginStateEnum.RESET_PASSWORD)}
								size="small"
							>
								{t("sys.login.forgetPassword")}
							</Button>
						</Col> */}
          </Row>
        </Form.Item>
        <Form.Item>
          <Button type='primary' htmlType='submit' className='w-full' loading={loading}>
            {t('sys.login.loginButton')}
          </Button>
        </Form.Item>

        <Divider />

        <div className='text-[14px] text-[#4F5464]'>
          登录即表示您已阅读并同意
          <span
            className='text-primary cursor-pointer mx-[2px]'
            onClick={() => viewAgreement('userAgreement')}>
            用户协议
          </span>
          和
          <span
            className='text-primary cursor-pointer ml-[2px]'
            onClick={() => viewAgreement('privacyPolicy')}>
            隐私权政策
          </span>
        </div>
        <div className='mt-[50px] text-[12px] leading-[22px] text-[#828797]'>
          温馨提示:建议使用谷歌、Microsoft Edge，版本 80及以上浏览器，360浏览器请使用极速模式
        </div>

        <Divider />

        <div className='text-[#BBBFC3] mt-[24px] text-center'>
          <div className='mb-[8px]'>
            <a
              className='!text-[#BBBFC3] !underline decoration-solid text-[12px] hover:!text-[#30363c]'
              href='https://beian.miit.gov.cn/'
              target='_blank'>
              京ICP备2022024690号-3
            </a>
          </div>
          <div className='text-[12px]'>
            版权公告 © 2023-2024 要易云科技（北京）有限责任公司。版权所有。
          </div>
        </div>

        {/* <Row align="middle" gutter={8}>
					<Col span={9} flex="1">
						<Button className="w-full !text-sm" onClick={() => setLoginState(LoginStateEnum.MOBILE)}>
							{t("sys.login.mobileSignInFormTitle")}
						</Button>
					</Col>
					<Col span={9} flex="1">
						<Button className="w-full !text-sm" onClick={() => setLoginState(LoginStateEnum.QR_CODE)}>
							{t("sys.login.qrSignInFormTitle")}
						</Button>
					</Col>
					<Col span={6} flex="1" onClick={() => setLoginState(LoginStateEnum.REGISTER)}>
						<Button className="w-full !text-sm">{t("sys.login.signUpFormTitle")}</Button>
					</Col>
				</Row> */}

        {/* <Divider className="!text-xs">{t("sys.login.otherSignIn")}</Divider> */}

        {/* <div className="flex cursor-pointer justify-around text-2xl">
					<AiFillGithub />
					<AiFillWechat />
					<AiFillGoogleCircle />
				</div> */}
        <UserAgreementModal {...userAgreementModalProps} />
        <PrivacyPolicyModal {...privacyPolicyModalProps} />
        <VerifyProvider success={verifySuccess}>
          <Verify
            ref={verifyRef}
            mode={'pop'}
            captchaType={'blockPuzzle'}
            imgSize={{ width: '330px', height: '155px' }}
          />
        </VerifyProvider>
      </Form>
    </>
  )
}

export default LoginForm
