/**
 * LP USDY 面板组件
 * 显示 USDY 相关操作
 */

import { useState } from 'react'
import { Button, Input } from 'antd'
import { formatUnits, parseUnits } from 'viem'
import { useAccount, useReadContract, useWriteContract, useWaitForTransactionReceipt, useChainId } from 'wagmi'
import { GAS_CONFIG, getContracts, getDecimals } from '@/config/contracts'
import { ERC20_BASE_ABI } from './types'
import { useToast } from '@/components/Toast'

interface LPUsdyPanelProps {
  show: boolean
  onToggle: () => void
}

export function LPUsdyPanel({
  show,
  onToggle,
}: LPUsdyPanelProps) {
  const { address } = useAccount()
  const { showToast } = useToast()
  // ===== 多链支持 =====
  const chainId = useChainId()
  const CONTRACTS = getContracts(chainId)
  const TOKEN_DECIMALS = getDecimals(chainId)

  const [transferForm, setTransferForm] = useState({
    recipient: '',
    amount: '',
  })

  // 读取 USDY 余额
  const { data: usdyBalance } = useReadContract({
    address: CONTRACTS.USDY as `0x${string}`,
    abi: ERC20_BASE_ABI,
    functionName: 'balanceOf',
    args: address ? [address] : undefined,
  })

  // 读取 USDY 授权额度
  const { data: usdyAllowance } = useReadContract({
    address: CONTRACTS.USDY as `0x${string}`,
    abi: ERC20_BASE_ABI,
    functionName: 'allowance',
    args: address ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
  })

  const { writeContract, data: hash, isPending } = useWriteContract()
  const { isLoading: isConfirming } = useWaitForTransactionReceipt({ hash })

  const isProcessing = isPending || isConfirming

  // 授权 USDY 给 Router
  const handleApproveUsdy = () => {
    if (!address) return
    writeContract({
      address: CONTRACTS.USDY as `0x${string}`,
      abi: ERC20_BASE_ABI,
      functionName: 'approve',
      args: [CONTRACTS.YT_REWARD_ROUTER, parseUnits('999999999', TOKEN_DECIMALS.USDY)],
      gas: GAS_CONFIG.SIMPLE,
    })
    showToast('info', '正在授权 USDY...')
  }

  // 转账 USDY
  const handleTransferUsdy = () => {
    if (!address || !transferForm.recipient || !transferForm.amount) return
    writeContract({
      address: CONTRACTS.USDY as `0x${string}`,
      abi: ERC20_BASE_ABI,
      functionName: 'transfer',
      args: [
        transferForm.recipient as `0x${string}`,
        parseUnits(transferForm.amount, TOKEN_DECIMALS.USDY),
      ],
      gas: GAS_CONFIG.STANDARD,
    })
    showToast('info', '正在转账 USDY...')
  }

  const inputStyle = {
    padding: '6px 8px',
    fontSize: '12px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    width: '100%',
    marginBottom: '6px',
  }

  return (
    <div style={{ marginTop: '12px', padding: '8px 12px', background: '#f9f9f9', borderRadius: '8px', border: '1px solid #e0e0e0' }}>
      <div
        style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' }}
        onClick={onToggle}
      >
        <h4 style={{ margin: 0, color: '#333', fontSize: '13px' }}>USDY 操作</h4>
        <span style={{ color: '#999', fontSize: '16px' }}>{show ? '▼' : '▶'}</span>
      </div>

      {show && (
        <div style={{ marginTop: '12px' }}>
          {/* USDY 余额信息 */}
          <div style={{
            padding: '10px',
            background: '#fff',
            borderRadius: '6px',
            marginBottom: '12px',
            border: '1px solid #e0e0e0'
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
              <span style={{ fontSize: '11px', color: '#666' }}>USDY 余额:</span>
              <span style={{ fontSize: '13px', fontWeight: 'bold', color: '#333' }}>
                {usdyBalance
                  ? Number(formatUnits(usdyBalance, TOKEN_DECIMALS.USDY)).toFixed(4)
                  : '0'} USDY
              </span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontSize: '11px', color: '#666' }}>Router 授权额度:</span>
              <span style={{ fontSize: '11px', color: '#666' }}>
                {usdyAllowance !== undefined
                  ? (Number(formatUnits(usdyAllowance as bigint, TOKEN_DECIMALS.USDY)) > 1000000
                      ? 'Unlimited'
                      : Number(formatUnits(usdyAllowance as bigint, TOKEN_DECIMALS.USDY)).toFixed(4))
                  : '0'}
              </span>
            </div>
          </div>

          {/* 授权按钮 */}
          <div style={{ marginBottom: '12px' }}>
            <Button
              type="primary"
              block
              onClick={handleApproveUsdy}
              disabled={isProcessing || !address}
              loading={isProcessing}
              style={{ fontSize: 13 }}
            >
              授权 USDY 给 Router (无限额度)
            </Button>
          </div>

          {/* 转账 USDY */}
          <div style={{
            padding: '10px',
            background: '#fff',
            borderRadius: '6px',
            border: '1px solid #e0e0e0'
          }}>
            <div style={{ fontSize: '11px', fontWeight: 'bold', color: '#333', marginBottom: '8px' }}>
              转账 USDY
            </div>
            <Input
              value={transferForm.recipient}
              onChange={(e) => setTransferForm({ ...transferForm, recipient: e.target.value })}
              style={{ marginBottom: '6px' }}
              placeholder="接收地址 (0x...)"
            />
            <div style={{ display: 'flex', gap: '8px' }}>
              <Input
                value={transferForm.amount}
                onChange={(e) => setTransferForm({ ...transferForm, amount: e.target.value })}
                style={{ flex: 1 }}
                placeholder="数量"
              />
              <Button
                size="small"
                onClick={() => {
                  if (usdyBalance) {
                    setTransferForm({ ...transferForm, amount: formatUnits(usdyBalance, TOKEN_DECIMALS.USDY) })
                  }
                }}
                style={{ whiteSpace: 'nowrap' }}
              >
                MAX
              </Button>
            </div>
            <Button
              type="primary"
              block
              onClick={handleTransferUsdy}
              disabled={isProcessing || !address || !transferForm.recipient || !transferForm.amount}
              loading={isProcessing}
              style={{ fontSize: 13, marginTop: 8 }}
            >
              转账
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}
