import {useEffect, useState} from 'react'
import {Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger} from '@/components/ui/dialog'
import {Button} from '@/components/ui/button'
import {Input} from '@/components/ui/input'
import Image from 'next/image'
import {useFormContext} from 'react-hook-form'
import {LoginSchema} from './login-card'
import {toast} from 'sonner'
import {sendSMS} from '@/actions/verify'

const seed = () => Date.now()

export type CaptchaProps = {
}

export default function Captcha(props: CaptchaProps) {
  const [countdown, setCountdown] = useState(0)

  const [code, setCode] = useState('')
  const [url, setUrl] = useState('/captcha?t=' + seed())
  const [show, setShow] = useState(false)
  const form = useFormContext<LoginSchema>()
  const username = form.watch('username')

  const setShowWithCheck = async (value: boolean) => {
    setShow(value && await form.trigger('username'))
  }

  const refreshCaptcha = () => {
    setUrl('/captcha?t=' + seed())
    setCode('')
  }

  const sendCode = async () => {
    try {
      if (!code.length) {
        throw new Error('请输入图形验证码')
      }

      const valid = await form.trigger('username')
      if (!valid) {
        throw new Error('请输入正确的手机号')
      }

      const resp = await sendSMS({
        phone: username,
        captcha: code,
      })
      if (!resp.success) {
        throw new Error(`验证码发送失败: ${resp.message}`)
      }

      setCountdown(60)
      setShow(false)
      toast.success('验证码已发送')
    }
    catch (e) {
      refreshCaptcha()
      toast.error('验证码发送失败', {
        description: (e as Error).message,
      })
    }
  }

  useEffect(() => {
    const interval = setInterval(() => {
      if (countdown > 0) {
        setCountdown(countdown - 1)
      }
    }, 1000)
    return () => clearInterval(interval)
  }, [countdown])

  return (
    <Dialog open={show} onOpenChange={setShowWithCheck}>
      <DialogTrigger asChild>
        <Button
          type="button"
          theme="outline"
          className="whitespace-nowrap h-10"
          disabled={countdown > 0}
        >
          {countdown > 0 ? `${countdown}秒后重发` : '获取验证码'}
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>人机验证</DialogTitle>
          <DialogDescription>请在下方输入验证码</DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div className="flex justify-between items-center">
            <Image
              unoptimized
              src={url}
              alt="验证码"
              width={180}
              height={50}
              className="border cursor-pointer"
              onClick={refreshCaptcha}
            />
            <Button
              theme="outline"
              onClick={refreshCaptcha}
              className="text-sm"
            >
              刷新
            </Button>
          </div>
          <Input
            placeholder="请输入图形验证码"
            value={code}
            onChange={e => setCode(e.target.value)}
            className="w-full"
          />
        </div>
        <DialogFooter>
          <DialogClose asChild>
            <Button
              theme="outline"
              onClick={() => setShow(false)}
              className="mr-2"
            >
              取消
            </Button>
          </DialogClose>
          <Button onClick={sendCode}>
            确认
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
