import { useEffect, useState } from 'react'
import { Tabs, Form, Input, Button } from 'antd'
import type { TabsProps } from 'antd'
import sso from '@src/lib/http/sso'
import type { modalType, LoginTypeProps, RegisterType } from './types'
import router from '@src/router/router'
import styles from './index.module.css'
import { debounce } from 'lodash'
import { useSearchParams } from 'react-router-dom'
const imgUrl = new URL('@assets/images/login_bg.png', import.meta.url).href 

export default function Login() {
  const [loginType, setLoginType] = useState<modalType>('login')
  const [activeTab, setActiveTab] = useState<string>('1')
  const [searchParams] = useSearchParams()

  function login() {
    if (searchParams.has('redirectUrl')) {
      router.navigate(decodeURIComponent(searchParams.get('redirectUrl') as string))
    }else{
      sessionStorage.removeItem('advertiserId')
      router.navigate('/')
    }
  }

  function editPassword() {
    setLoginType('register')
  }

  function backToLogin() {
    setLoginType('login')
  }

  function tabChange(tab: string) {
    setActiveTab(tab)
  }

  const items: TabsProps['items'] = [
    {
      key: '1',
      label: '账号登录',
      children: <AccountLogin activeTab={activeTab} onLogin={login} onEditPassword={editPassword}/>
    },
    // {
    //   key: '2',
    //   label: '短信登录',
    //   children: <SMSlogin activeTab={activeTab} onLogin={login} onEditPassword={editPassword} />
    // }
  ]

  return (
    <div className={styles['login-contianer']}>
      <div className={styles['logo-banner']}>
        <div className={styles['logo-icon']}></div>
        <div className={styles['logo-title']}>
          AD <span>|</span> 优量圈
        </div>
      </div>
      <div className={styles['login-body']}>
        <div className={styles['login-bg']}>
          <img src={imgUrl} alt="" />
        </div>
        <div className={styles['login-box']}>
          {loginType === 'login' && <Tabs onChange={tabChange} defaultActiveKey="1" items={items} centered />}
          {loginType === 'register' && <Register backToLogin={backToLogin}/>}
        </div>
      </div>
      {/* <div className={styles['login-footer']}>
        <p>客服电话 0731-85679198、18974809627 | 客服邮箱：piaoquankefu@piaoquantv.com</p>
        <p>ICP备案：湘B2-20180063 | <span onClick={() => window.open('https://beian.miit.gov.cn/')}>湘ICP备16013107-06号</span> | <span onClick={() => window.open('https://beian.mps.gov.cn/#/query/webSearch')}>湘公网安备：43019002001624</span></p>
      </div> */}
    </div>
  )
}

// 密码登录
function AccountLogin({ onLogin, activeTab }: LoginTypeProps) {
  const [form] = Form.useForm()

  useEffect(() => {
    form.resetFields()
  }, [activeTab])

  function login() {
    form.validateFields().then(res => {
      const { account, password } = res
      fetchLogin(account, password)
    })
  }

  function validator() {
    const account = form.getFieldValue('account')

    if (!account)
      return Promise.resolve()

    const phoneRegx = /^1[3456789]\d{9}$/
    const emailRegx = /^\w+@\w+(\.\w+)+$/

    if (phoneRegx.test(account) || emailRegx.test(account))
      return Promise.resolve()
    
    return Promise.reject('请输入合法账号')
  }

  const fetchLogin = debounce((account, password) => {
    sso.login(account, password).then(res => {
      res && onLogin()
    })
  }, 500)
  
  return (
    <div className={styles['account-login']}>
      <Form form={form}>
        <Form.Item name='account' validateTrigger='onBlur' rules={[{ required: true, message: '请输入手机号/邮箱', }, { validator }]}>
          <Input placeholder='请输入手机号/邮箱' allowClear />
        </Form.Item>
        <Form.Item name='password' rules={[{ required: true, message: '请输入密码' }]}>
          <Input.Password placeholder='请输入密码' allowClear />
        </Form.Item>
        <Form.Item name='loginBtn'>
          <Button type="primary" block onClick={login}>登录</Button>
        </Form.Item>
      </Form>
      {/* <p className={styles['forget-password']} onClick={onEditPassword}>忘记密码？</p> */}
    </div>
  )
}

// 短信登录
// function SMSlogin({ onLogin, onEditPassword, activeTab }: LoginTypeProps) {
//   const [smsText, setSmsText] = useState('获取验证码')
//   const [verificationDisabled, setVerificationDisabled] = useState(false)
//   const [form] = Form.useForm()

//   useEffect(() => {
//     form.resetFields()
//   }, [activeTab])

//   function login() {
//     form.validateFields().then(res => {
//       const { verificationCode, phone } = res
//       fetchLogin(phone, verificationCode)
//     })
//   }

//   const fetchLogin = debounce((phone, verificationCode) => {
//     sso.loginBySendCode(phone, verificationCode).then(res => {
//       res && onLogin()
//     })
//   }, 500)

//   function verificationCode() {
//     form.validateFields(['phone']).then(res => {
//       const { phone } = res
//       sso.sendCode(phone).then(res => {
//         res && countdown()
//       })
//     })
//   }

//   function countdown() {
//     let count = 59
//     setVerificationDisabled(true)
//     setSmsText(`${count--}`)

//     const interval = setInterval(() => {
//       setSmsText(`${count--}`)
//       if (interval && count === 0) {
//         clearInterval(interval)
//         setVerificationDisabled(false)
//         setSmsText('获取验证码')
//       }
//     }, 1000)
//   }

//   function validator() {
//     const phone = form.getFieldValue('phone')

//     if (!phone)
//       return Promise.resolve()

//     const phoneRegx = /^1[3456789]\d{9}$/

//     if (phoneRegx.test(phone))
//       return Promise.resolve()
    
//     return Promise.reject('请输入合法手机号')
//   }

//   return (
//     <div className={styles['sms-login']}>
//       <Form form={form}>
//         <Form.Item name='phone' validateTrigger='onBlur' rules={[{ required: true, message: '请输入手机号' }, { validator }]}>
//           <Input placeholder='请输入手机号' allowClear />
//         </Form.Item>
//         <Form.Item name='verificationCode' rules={[{ required: true, message: '请输入验证码' }]}>
//           <div className={styles['msg-password']}>
//             <Input placeholder='请输入验证码' allowClear />
//             <Button type="primary" onClick={verificationCode} disabled={verificationDisabled}>
//               {smsText}
//             </Button>
//           </div>
//         </Form.Item>
//         <Form.Item name='loginBtn'>
//           <Button type="primary" block onClick={login}>登录</Button>
//         </Form.Item>
//       </Form>
//       <p className={styles['forget-password']} onClick={onEditPassword}>忘记密码？</p>
//     </div>
//   )
// }

// 忘记密码
function Register({ backToLogin }: RegisterType) {
  const [smsText, setSmsText] = useState('获取验证码')
  const [verificationDisabled, setVerificationDisabled] = useState(false)
  const [form] = Form.useForm()

  useEffect(() => {
    form.resetFields()
  }, [])

  function submit() {
    form.validateFields().then(res => {
      const { phone, verificationCode, newPassword } = res
      fetchSubmit(phone, verificationCode, newPassword)
    })
  }

  const fetchSubmit = debounce((phone, verificationCode, newPassword) => {
    sso.forgotLoginPassword(phone, verificationCode, newPassword).then(res => {
      res && backToLogin()
    })
  }, 500)

  function verificationCode() {
    form.validateFields(['phone']).then(res => {
      const { phone } = res
      sso.sendCode(phone).then(res => {
        res && countdown()
      })
    })
  }

  function countdown() {
    let count = 59
    setVerificationDisabled(true)
    setSmsText(`${count--}`)

    const interval = setInterval(() => {
      setSmsText(`${count--}`)
      if (interval && count === 0) {
        clearInterval(interval)
        setVerificationDisabled(false)
        setSmsText('获取验证码')
      }
    }, 1000)
  }

  function validator() {
    const phone = form.getFieldValue('phone')

    if (!phone)
      return Promise.resolve()

    const phoneRegx = /^1[3456789]\d{9}$/
    const emailRegx = /^\w+@\w+(\.\w+)+$/

    if (phoneRegx.test(phone) || emailRegx.test(phone))
      return Promise.resolve()
    
    return Promise.reject('请输入合法手机号')
  }

  return (
    <div className={styles.register}>
      <div className={styles.title}>
        忘记密码
      </div>
      <div className={styles['register-contianer']}>
        <Form form={form}>
          <Form.Item name='phone' validateTrigger='onBlur' rules={[{ required: true, message: '请输入手机号/邮箱' }, { validator }]}>
            <Input placeholder='请输入手机号/邮箱' allowClear />
          </Form.Item>
          <Form.Item name='verificationCode' rules={[{ required: true, message: '请输入验证码' }]}>
            <div className={styles['msg-password']}>
              <Input placeholder='请输入验证码' allowClear />
              <Button type="primary" onClick={verificationCode} disabled={verificationDisabled}>
                {smsText}
              </Button>
            </div>
          </Form.Item>
          <Form.Item name='newPassword' rules={[{ required: true, message: '请输入新密码' }]}>
            <Input.Password placeholder='请输入新密码' allowClear />
          </Form.Item>
          <Form.Item name='loginBtn'>
            <Button type="primary" block onClick={submit}>确认</Button>
          </Form.Item>
          <Form.Item name='backBtn'>
            <Button block onClick={backToLogin}>返回</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
