import { useRef, useState } from 'react'
import styles from './SwapConfirmModal.module.css'

interface SwapData {
  details: {
    currencyIn: { amountFormatted: string; amountUsd: string; currency: { symbol: string } }
    currencyOut: { amountFormatted: string; amountUsd: string; currency: { symbol: string } }
    totalImpact: { percent: string }
    rate: string
  }
  fees: {
    gas: { amountUsd: string }
  }
}

interface Props {
  data: SwapData
  insufficientBalance?: boolean
  onConfirm: () => void
  onClose: () => void
}

export function SwapConfirmModal({ data, insufficientBalance, onConfirm, onClose }: Props) {
  const { details, fees } = data
  const { currencyIn, currencyOut, totalImpact, rate } = details
  const [closing, setClosing] = useState(false)
  // Which action to run once the exit animation finishes.
  const pendingAction = useRef<'close' | 'confirm'>('close')

  const impactPercent = parseFloat(totalImpact.percent)
  const rateFormatted = parseFloat(rate).toFixed(4)

  // 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}>
              {currencyIn.amountFormatted} {currencyIn.currency.symbol}
            </span>
            <span className={styles.tokenUsd}>≈ ${currencyIn.amountUsd}</span>
          </div>

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

          <div className={styles.token}>
            <span className={styles.tokenLabel}>Получаете</span>
            <span className={styles.tokenAmount}>
              {currencyOut.amountFormatted} {currencyOut.currency.symbol}
            </span>
            <span className={styles.tokenUsd}>≈ ${currencyOut.amountUsd}</span>
          </div>
        </div>

        <div className={styles.details}>
          <div className={styles.row}>
            <span className={styles.rowLabel}>Курс</span>
            <span className={styles.rowValue}>
              1 {currencyIn.currency.symbol} = {rateFormatted} {currencyOut.currency.symbol}
            </span>
          </div>
          <div className={styles.row}>
            <span className={styles.rowLabel}>Комиссия сети</span>
            <span className={styles.rowValue}>${fees.gas.amountUsd}</span>
          </div>
          <div className={styles.row}>
            <span className={styles.rowLabel}>Влияние на цену</span>
            <span className={`${styles.rowValue} ${impactPercent < 0 ? styles.impact : ''}`}>
              {totalImpact.percent}%
            </span>
          </div>
        </div>

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

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