import { useEffect, useState } from 'react'
import { QRCodeSVG } from 'qrcode.react'
import { useWalletAddresses, type Chain } from '@features/wallet'
import styles from './ReceiveModal.module.css'

const CHAIN_LABEL: Record<Chain, string> = {
  ETH: 'Ethereum',
  BSC: 'BSC Smart Chain',
  BTC: 'Bitcoin',
  TRX: 'Tron',
  SOL: 'Solana',
}

interface ReceiveModalProps {
  open: boolean
  onClose: () => void
  chain: Chain
}

export function ReceiveModal({ open, onClose, chain }: ReceiveModalProps) {
  const { data: addresses, isLoading, isError } = useWalletAddresses()
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    if (!open) return
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [open, onClose])

  useEffect(() => {
    if (!open) setCopied(false)
  }, [open])

  if (!open) return null

  const entry = addresses?.find(a => a.chain === chain)
  const address = entry?.address ?? ''

  function handleCopy() {
    if (!address) return
    navigator.clipboard.writeText(address).then(() => {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    })
  }

  function handleOverlay(e: React.MouseEvent<HTMLDivElement>) {
    if (e.target === e.currentTarget) onClose()
  }

  return (
    <div className={styles.overlay} onMouseDown={handleOverlay}>
      <div className={styles.dialog}>
        <div className={styles.header}>
          <span className={styles.title}>Получить {CHAIN_LABEL[chain]}</span>
          <button className={styles.closeBtn} type="button" onClick={onClose} aria-label="Закрыть">✕</button>
        </div>

        <div className={styles.body}>
          {isLoading && (
            <div className={styles.skeleton} />
          )}

          {isError && (
            <p className={styles.error}>Не удалось загрузить адрес. Попробуйте позже.</p>
          )}

          {!isLoading && !isError && (
            <>
              <label className={styles.label}>Ваш {chain}-адрес</label>
              <div className={styles.fieldRow}>
                <input
                  className={styles.addressInput}
                  type="text"
                  readOnly
                  value={address}
                  onFocus={e => e.target.select()}
                />
                <button
                  className={`${styles.copyBtn} ${copied ? styles.copyBtnDone : ''}`}
                  type="button"
                  onClick={handleCopy}
                  disabled={!address}
                >
                  {copied ? 'Скопировано!' : 'Копировать'}
                </button>
              </div>
              {address && (
                <div className={styles.qrWrap}>
                  <QRCodeSVG
                    value={address}
                    size={196}
                    level="M"
                    bgColor="#ffffff"
                    fgColor="#000000"
                    marginSize={2}
                  />
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
