'use client'

import { Turnstile } from '@marsidev/react-turnstile'
import axios from 'axios'
import { useState } from 'react'

export default function CaptchaCodePage () {
  const [token, setToken] = useState<string | null>(null)
  const [code, setCode] = useState<string | null>(null)
  const [result, setResult] = useState<number>(-1)
  const [showCopied, setShowCopied] = useState<boolean>(false)

  return (
    <div className='box'>
      <p className='mb-4 -mt-2 text-center'>
        Verify you are human to get a code
      </p>
      <Turnstile
        siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY ?? ''}
        onSuccess={async token => {
          setToken(token)
          setResult(0)
          try {
            const result = await axios.post('/api/get-verify-code', {
              token
            })
            if (result.data.success) {
              setCode(result.data.data)
              setResult(2)
            } else {
              setResult(3)
            }
          } catch {
            setResult(3)
          }
        }}
        onError={() => setResult(1)}
        hidden={result != -1}
      />
      <p className='mt-2 -mb-2 text-center text-sm' hidden={result == -1}>
        {result == 0
          ? 'Getting verification code...'
          : result == 1
          ? 'Unable to verify captcha, please reload page.'
          : result == 2
          ? 'Here is your verification code. It will in 10 minutes or when used.'
          : 'Failed to get verification code. Please try again later.'}
      </p>
      <p
        className='bg-[rgb(64,64,88)] border border-[rgb(88,88,112)] hover:bg-[rgb(88,88,112)] hover:border-[rgb(112,112,136)] rounded-md px-2 py-1 mt-4 transition-colors text-center cursor-pointer'
        hidden={result != 2}
        onClick={async () => {
          navigator.clipboard.writeText(code ?? '')
          if (showCopied) return
          setShowCopied(true)
          setTimeout(() => {
            setShowCopied(false)
          }, 3000)
        }}
      >
        {code ?? 'N/A'}
      </p>
      <p
        className='text-blue-500 text-center mt-2 -mb-4'
        hidden={!showCopied || result != 2}
      >
        Copied to clipboard!
      </p>
    </div>
  )
}
