/**
 * TransactionModal Component
 *
 * Modal that shows transaction progress during blockchain operations.
 *
 * States:
 * - Pending: Waiting for user to sign in MetaMask
 * - Confirming: Transaction submitted, waiting for block confirmation
 * - Success: Transaction confirmed
 * - Error: Transaction failed
 *
 * Features:
 * - Animated loading states
 * - Transaction hash with explorer link
 * - Retry button on error
 * - Auto-close on success (optional)
 */

import { FC, useEffect } from 'react'
import { Modal } from '@/components/common/Modal'

interface TransactionModalProps {
  isOpen: boolean
  status: 'idle' | 'pending' | 'confirming' | 'success' | 'error'
  message?: string
  txHash?: string | null
  chainId?: number
  onClose: () => void
  onRetry?: () => void
  autoCloseOnSuccess?: boolean
  autoCloseDelay?: number // milliseconds
}

export const TransactionModal: FC<TransactionModalProps> = ({
  isOpen,
  status,
  message,
  txHash,
  chainId = 11155111,
  onClose,
  onRetry,
  autoCloseOnSuccess = false,
  autoCloseDelay = 3000
}) => {
  /**
   * Auto-close on success
   */
  useEffect(() => {
    if (status === 'success' && autoCloseOnSuccess) {
      const timer = setTimeout(() => {
        onClose()
      }, autoCloseDelay)

      return () => clearTimeout(timer)
    }
  }, [status, autoCloseOnSuccess, autoCloseDelay, onClose])

  /**
   * Get block explorer URL
   */
  const getExplorerUrl = (hash: string) => {
    const explorers: Record<number, string> = {
      1: 'https://etherscan.io',
      11155111: 'https://sepolia.etherscan.io',
      137: 'https://polygonscan.com',
      80001: 'https://mumbai.polygonscan.com'
    }

    const baseUrl = explorers[chainId] || explorers[11155111]
    return `${baseUrl}/tx/${hash}`
  }

  /**
   * Render content based on status
   */
  const renderContent = () => {
    switch (status) {
      case 'pending':
        return (
          <div className="text-center py-8">
            <div className="inline-flex items-center justify-center w-16 h-16 mb-4 rounded-full bg-blue-100">
              <svg className="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>

            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              Confirm Transaction
            </h3>

            <p className="text-sm text-gray-600 mb-4">
              {message || 'Please confirm the transaction in your wallet'}
            </p>

            <div className="text-xs text-gray-500">
              Waiting for wallet confirmation...
            </div>
          </div>
        )

      case 'confirming':
        return (
          <div className="text-center py-8">
            <div className="inline-flex items-center justify-center w-16 h-16 mb-4">
              <svg className="animate-spin h-12 w-12 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            </div>

            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              Confirming Transaction
            </h3>

            <p className="text-sm text-gray-600 mb-4">
              {message || 'Your transaction is being processed on the blockchain'}
            </p>

            <div className="space-y-2">
              <div className="flex items-center justify-center gap-2 text-xs text-gray-600">
                <div className="w-2 h-2 bg-blue-600 rounded-full animate-pulse"></div>
                <span>Waiting for block confirmation...</span>
              </div>

              {txHash && (
                <a
                  href={getExplorerUrl(txHash)}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 underline"
                >
                  <svg className="h-3 w-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                  View on Explorer
                </a>
              )}
            </div>

            <p className="text-xs text-gray-500 mt-4">
              Do not close this window
            </p>
          </div>
        )

      case 'success':
        return (
          <div className="text-center py-8">
            <div className="inline-flex items-center justify-center w-16 h-16 mb-4 rounded-full bg-green-100">
              <svg className="w-10 h-10 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
              </svg>
            </div>

            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              Transaction Confirmed!
            </h3>

            <p className="text-sm text-gray-600 mb-4">
              {message || 'Your transaction has been successfully processed'}
            </p>

            {txHash && (
              <div className="space-y-2 mb-6">
                <div className="text-xs text-gray-500">Transaction Hash</div>
                <code className="block text-xs bg-gray-100 px-3 py-2 rounded font-mono break-all">
                  {txHash}
                </code>
                <a
                  href={getExplorerUrl(txHash)}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800 underline"
                >
                  <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                  View on Block Explorer
                </a>
              </div>
            )}

            <button
              onClick={onClose}
              className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
            >
              Close
            </button>
          </div>
        )

      case 'error':
        return (
          <div className="text-center py-8">
            <div className="inline-flex items-center justify-center w-16 h-16 mb-4 rounded-full bg-red-100">
              <svg className="w-10 h-10 text-red-600" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
            </div>

            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              Transaction Failed
            </h3>

            <p className="text-sm text-gray-600 mb-6">
              {message || 'Your transaction could not be processed'}
            </p>

            <div className="flex gap-3 justify-center">
              {onRetry && (
                <button
                  onClick={onRetry}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  Try Again
                </button>
              )}
              <button
                onClick={onClose}
                className="px-6 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        )

      default:
        return null
    }
  }

  return (
    <Modal
      isOpen={isOpen && status !== 'idle'}
      onClose={status === 'confirming' ? () => {} : onClose} // Prevent closing during confirmation
      title=""
    >
      {renderContent()}
    </Modal>
  )
}

/**
 * Compact transaction status indicator (not a modal)
 */
export const TransactionStatusIndicator: FC<{
  status: TransactionModalProps['status']
  txHash?: string
  chainId?: number
}> = ({ status, txHash, chainId }) => {
  const getExplorerUrl = (hash: string) => {
    const explorers: Record<number, string> = {
      1: 'https://etherscan.io',
      11155111: 'https://sepolia.etherscan.io',
      137: 'https://polygonscan.com',
      80001: 'https://mumbai.polygonscan.com'
    }
    return `${explorers[chainId || 11155111]}/tx/${hash}`
  }

  if (status === 'idle') return null

  const statusConfig = {
    pending: { color: 'yellow', icon: '⏳', text: 'Pending' },
    confirming: { color: 'blue', icon: '🔄', text: 'Confirming' },
    success: { color: 'green', icon: '✓', text: 'Confirmed' },
    error: { color: 'red', icon: '✗', text: 'Failed' }
  }

  const config = statusConfig[status]

  return (
    <div className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-${config.color}-100 text-${config.color}-800`}>
      <span>{config.icon}</span>
      <span className="text-sm font-medium">{config.text}</span>
      {txHash && status !== 'pending' && (
        <a
          href={getExplorerUrl(txHash)}
          target="_blank"
          rel="noopener noreferrer"
          className="text-xs underline"
        >
          View
        </a>
      )}
    </div>
  )
}
