import { useState, useEffect } from 'react'
import { useSendWallet } from '@features/wallet'
import { CHAIN_CONFIG, CHAIN_TOKENS, type Chain, type FeeTier } from '../model/sendTypes'
import styles from './SendModal.module.css'

export interface SendModalToken {
  ticker: string
  name: string
  logo?: string
  color: string
  bal: string
}

interface Props {
  open: boolean
  onClose: () => void
  network: Chain
  /** Wallet token rows — used only for balance lookup in the "Макс" hint */
  tokens?: SendModalToken[]
  /** Pre-select a token in the network token list (ticker or empty string = native) */
  initialToken?: string
}

const SPEEDS: { value: FeeTier; label: string }[] = [
  { value: 'slow',   label: 'Медленно'  },
  { value: 'normal', label: 'Нормально' },
  { value: 'fast',   label: 'Быстро'    },
]

function extractErrorMessage(err: unknown): string {
  if (err instanceof Error) return err.message
  if (err && typeof err === 'object') {
    const e = err as Record<string, unknown>
    if (typeof e.message === 'string') return e.message
    if (typeof e.error === 'string') return e.error
    if (Array.isArray(e.detail) && (e.detail[0] as Record<string, unknown>)?.msg)
      return String((e.detail[0] as Record<string, unknown>).msg)
  }
  return 'Что-то пошло не так. Попробуйте ещё раз.'
}

export function SendModal({ open, onClose, network, tokens = [], initialToken = '' }: Props) {
  const cfg = CHAIN_CONFIG[network]
  const networkTokens = CHAIN_TOKENS[network] as readonly string[]

  const [selectedToken, setSelectedToken] = useState(initialToken)
  const [speed, setSpeed]                 = useState<FeeTier>('normal')
  const [address, setAddress]             = useState('')
  const [amount, setAmount]               = useState('')
  const [openDropdown, setOpenDropdown]   = useState<'token' | 'speed' | null>(null)

  const mutation = useSendWallet()

  const speedLabel  = SPEEDS.find((s) => s.value === speed)?.label ?? 'Нормально'
  const tokenLabel  = selectedToken === '' ? cfg.nativeSymbol : selectedToken
  const walletMatch = tokens.find(
    (t) => t.ticker === (selectedToken === '' ? cfg.nativeSymbol : selectedToken),
  )

  useEffect(() => { setSelectedToken(initialToken) }, [initialToken])
  useEffect(() => { setSelectedToken('') }, [network])

  useEffect(() => {
    if (mutation.isSuccess) onClose()
  }, [mutation.isSuccess, onClose])

  useEffect(() => {
    if (!open) {
      setAddress('')
      setAmount('')
      setOpenDropdown(null)
      mutation.reset()
      return
    }
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
    document.addEventListener('keydown', handler)
    return () => document.removeEventListener('keydown', handler)
  }, [open, onClose]) // eslint-disable-line react-hooks/exhaustive-deps

  if (!open) return null

  const showToken   = cfg.hasToken
  const showFeeTier = cfg.hasFeeTier
  const showSelects = showToken || showFeeTier
  const selectsCols = showToken && showFeeTier ? 2 : 1

  function handleOverlayClick() {
    if (openDropdown) { setOpenDropdown(null) } else { onClose() }
  }

  function toBaseUnits(value: string, decimals: number): string {
    const [intPart, fracPart = ''] = value.split('.')
    const frac = fracPart.slice(0, decimals).padEnd(decimals, '0')
    return (BigInt(intPart || '0') * (10n ** BigInt(decimals)) + BigInt(frac || '0')).toString()
  }

  function handleSubmit() {
    const isNative = selectedToken === ''
    const convertedAmount = isNative ? toBaseUnits(amount, cfg.nativeDecimals) : amount
    mutation.mutate({
      chain: network,
      to: address,
      amount: convertedAmount,
      ...(selectedToken ? { token: selectedToken } : {}),
      ...(cfg.hasFeeTier ? { feeTier: speed } : {}),
    })
  }

  return (
    <div className={styles.overlay} onClick={handleOverlayClick}>
      <div className={styles.dialog} onClick={(e) => e.stopPropagation()}>

        {/* Header */}
        <div className={styles.header}>
          <div className={styles.headerLeft}>
            <span className={styles.chainDot} style={{ background: cfg.color }} />
            <span className={styles.title}>Отправить · {cfg.label}</span>
          </div>
          <button className={styles.close} onClick={onClose} type="button" aria-label="Закрыть">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
              <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
            </svg>
          </button>
        </div>

        {/* Token + Speed selects */}
        {showSelects && (
          <div
            className={styles.selectsRow}
            style={{ gridTemplateColumns: `repeat(${selectsCols}, 1fr)` }}
          >
            {showToken && (
              <div className={styles.selectGroup}>
                <label className={styles.selectLabel}>Токен</label>
                <button
                  type="button"
                  className={`${styles.selectTrigger} ${openDropdown === 'token' ? styles.selectTriggerOpen : ''}`}
                  onClick={() => setOpenDropdown((d) => (d === 'token' ? null : 'token'))}
                >
                  <span className={styles.tokenDot} style={{ background: cfg.color }}>
                    {tokenLabel[0]}
                  </span>
                  <span className={styles.selectValue}>{tokenLabel}</span>
                  <svg
                    className={`${styles.chevron} ${openDropdown === 'token' ? styles.chevronOpen : ''}`}
                    width="12" height="12" viewBox="0 0 12 12" fill="none"
                  >
                    <path d="M2 4l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
                {openDropdown === 'token' && (
                  <div className={styles.dropdown}>
                    <button
                      type="button"
                      className={`${styles.dropdownItem} ${selectedToken === '' ? styles.dropdownItemActive : ''}`}
                      onClick={() => { setSelectedToken(''); setOpenDropdown(null) }}
                    >
                      <span className={styles.tokenDot} style={{ background: cfg.color }}>
                        {cfg.nativeSymbol[0]}
                      </span>
                      <span className={styles.dropdownTicker}>{cfg.nativeSymbol}</span>
                      <span className={styles.dropdownName}>Нативный</span>
                    </button>
                    {networkTokens.map((tok) => (
                      <button
                        key={tok}
                        type="button"
                        className={`${styles.dropdownItem} ${selectedToken === tok ? styles.dropdownItemActive : ''}`}
                        onClick={() => { setSelectedToken(tok); setOpenDropdown(null) }}
                      >
                        <span className={styles.tokenDot} style={{ background: 'rgba(255,255,255,0.12)' }}>
                          {tok[0]}
                        </span>
                        <span className={styles.dropdownTicker}>{tok}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}

            {showFeeTier && (
              <div className={styles.selectGroup}>
                <label className={styles.selectLabel}>Скорость</label>
                <button
                  type="button"
                  className={`${styles.selectTrigger} ${openDropdown === 'speed' ? styles.selectTriggerOpen : ''}`}
                  onClick={() => setOpenDropdown((d) => (d === 'speed' ? null : 'speed'))}
                >
                  <span className={`${styles.speedDot} ${styles[`speedDot_${speed}`]}`} />
                  <span className={styles.selectValue}>{speedLabel}</span>
                  <svg
                    className={`${styles.chevron} ${openDropdown === 'speed' ? styles.chevronOpen : ''}`}
                    width="12" height="12" viewBox="0 0 12 12" fill="none"
                  >
                    <path d="M2 4l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                </button>
                {openDropdown === 'speed' && (
                  <div className={styles.dropdown}>
                    {SPEEDS.map((s) => (
                      <button
                        key={s.value}
                        type="button"
                        className={`${styles.dropdownItem} ${s.value === speed ? styles.dropdownItemActive : ''}`}
                        onClick={() => { setSpeed(s.value); setOpenDropdown(null) }}
                      >
                        <span className={`${styles.speedDot} ${styles[`speedDot_${s.value}`]}`} />
                        <span>{s.label}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Address */}
        <div className={styles.field}>
          <label className={styles.fieldLabel}>Адрес кошелька</label>
          <input
            className={styles.input}
            type="text"
            placeholder={cfg.addressPlaceholder}
            value={address}
            onChange={(e) => setAddress(e.target.value)}
            autoComplete="off"
            spellCheck={false}
          />
        </div>

        {/* Amount */}
        <div className={styles.field}>
          <label className={styles.fieldLabel}>Количество</label>
          <div className={styles.amountWrap}>
            <input
              className={`${styles.input} ${styles.amountInput}`}
              type="number"
              placeholder="0.00"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              min="0"
              step="any"
            />
            <span className={styles.amountTicker}>{tokenLabel}</span>
          </div>
          {walletMatch && (
            <div className={styles.maxHint}>
              Макс:{' '}
              <button
                type="button"
                className={styles.maxBtn}
                onClick={() => setAmount(walletMatch.bal)}
              >
                {walletMatch.bal} {tokenLabel}
              </button>
            </div>
          )}
        </div>

        {/* Error */}
        {mutation.isError && (
          <div className={styles.errorMsg}>
            {extractErrorMessage(mutation.error)}
          </div>
        )}

        <button
          className={styles.submitBtn}
          type="button"
          disabled={mutation.isPending}
          onClick={handleSubmit}
        >
          {mutation.isPending ? 'Отправка…' : 'Отправить'}
        </button>
      </div>
    </div>
  )
}
