import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQueryClient } from '@tanstack/react-query'
import { PrimaryButton } from '@shared/ui'
import { useMe } from '@features/auth'
import { ROUTES } from '@shared/config/routes'
import logo from '@shared/assets/logo-full-white.png'
import { useKyc } from '../model/useKyc'
import { KycModal } from './KycModal'
import styles from './KycWidget.module.css'

export function KycWidget() {
  const { trigger, data, isLoading, isError } = useKyc()
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const { data: me } = useMe({ refetchInterval: data ? 5000 : false })

  useEffect(() => {
    if (me?.kyc_verified) {
      navigate(ROUTES.SEED_PHRASE, { replace: true })
    }
  }, [me?.kyc_verified, navigate])

  const handleClose = () => {
    queryClient.invalidateQueries({ queryKey: ['me'] })
  }

  return (
    <>
      <div className={styles.card}>
        <div className={styles.logo}>
          <img src={logo} alt="ЭКСА" />
        </div>

        <div className={styles.iconWrapper}>
          <svg width="38" height="38" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M12 2L3 6v6c0 5.25 3.75 10.15 9 11.35C17.25 22.15 21 17.25 21 12V6l-9-4z"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <path
              d="M9 12l2 2 4-4"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </div>

        <p className={styles.description}>
          Для продолжения работы необходимо пройти KYC верификацию
        </p>

        <div className={styles.buttonWrapper}>
          <PrimaryButton
            label={isLoading ? 'Загрузка...' : 'Подтвердить личность'}
            type="button"
            onClick={() => trigger()}
            disabled={isLoading}
          />
        </div>

        {isError && (
          <p className={styles.error}>
            Произошла ошибка. Попробуй перезагрузить страницу и попробовать снова.
          </p>
        )}
      </div>

      {data && <KycModal data={data} onClose={handleClose} />}
    </>
  )
}
