import { useRef, useState } from 'react'
import type { TrxSwapQuoteData } from '@features/wallet'
import styles from './TrxConfirmModal.module.css'

interface Props {
  quote: TrxSwapQuoteData
  fromSymbol: string
  toSymbol: string
  amountHuman: string
  insufficientBalance?: boolean
  onConfirm: () => void
  onClose: () => void
}

export function TrxConfirmModal({ quote, fromSymbol, toSymbol, amountHuman, insufficientBalance, onConfirm, onClose }: Props) {
  const { expectedOutFormatted, minOutFormatted, fees } = quote
  const [closing, setClosing] = useState(false)
  // Which action to run once the exit animation finishes.
  const pendingAction = useRef<'close' | 'confirm'>('close')

  // Trigger the exit animation; the real action fires on animation end so every
  // close path (×, backdrop, confirm) plays the same closing transition.
  function requestClose() {
    pendingAction.current = 'close'
    setClosing(true)
  }

  function requestConfirm() {
    pendingAction.current = 'confirm'
    setClosing(true)
  }

  function handleAnimationEnd() {
    if (!closing) return
    if (pendingAction.current === 'confirm') onConfirm()
    else onClose()
  }

  return (
    <div className={`${styles.overlay} ${closing ? styles.closing : ''}`} onClick={requestClose}>
      <div
        className={`${styles.card} ${closing ? styles.closing : ''}`}
        onClick={e => e.stopPropagation()}
        onAnimationEnd={handleAnimationEnd}
      >
        <div className={styles.header}>
          <span className={styles.title}>Подтвердить своп</span>
          <button className={styles.closeBtn} onClick={requestClose}>×</button>
        </div>

        <div className={styles.flow}>
          <div className={styles.token}>
            <span className={styles.tokenLabel}>Отдаёте</span>
            <span className={styles.tokenAmount}>{amountHuman} {fromSymbol}</span>
          </div>

          <div className={styles.arrow}>↓</div>

          <div className={styles.token}>
            <span className={styles.tokenLabel}>Получаете</span>
            <span className={styles.tokenAmount}>{expectedOutFormatted} {toSymbol}</span>
            <span className={styles.minOut}>Минимум: {minOutFormatted} {toSymbol}</span>
          </div>
        </div>

        <div className={styles.details}>
          <div className={styles.row}>
            <span className={styles.rowLabel}>Комиссия сети</span>
            <span className={styles.rowValue}>
              {fees.network.amountFormatted} {fees.network.asset} (≈${fees.network.amountUsd})
            </span>
          </div>
        </div>

        {insufficientBalance && (
          <p className={styles.warning}>
            Введённое количество превышает баланс кошелька — своп будет отклонён.
          </p>
        )}

        <button className={styles.confirmBtn} onClick={requestConfirm}>
          Подтвердить
        </button>
      </div>
    </div>
  )
}
