import React, {useState} from 'react'
import {FiRefreshCw, FiSend} from 'react-icons/fi'

import {SelectColumnFilter, Table} from '../../../components/mollecules'
import type {IAccountRowDetail} from '../../../global/type.tsx'
import type {Account, Balance} from '../../../generated/ManagingApi'
import {Ticker} from '../../../generated/ManagingApi'
import SwapModal from './SwapModal'
import SendTokenModal from './SendTokenModal'

interface IAccountRowDetailProps extends IAccountRowDetail {
  account: Account
}

const AccountRowDetails: React.FC<IAccountRowDetailProps> = ({
  balances,
  showTotal,
  account,
}) => {
  const [swapModalState, setSwapModalState] = useState<{
    isOpen: boolean
    fromTicker: Ticker | null
    availableAmount: number
  }>({
    isOpen: false,
    fromTicker: null,
    availableAmount: 0,
  })

  const [sendTokenModalState, setSendTokenModalState] = useState<{
    isOpen: boolean
    fromTicker: Ticker | null
    availableAmount: number
  }>({
    isOpen: false,
    fromTicker: null,
    availableAmount: 0,
  })

  const handleSwapClick = (balance: Balance) => {
    if (balance.tokenName && balance.amount) {
      // Convert tokenName to Ticker enum
      const ticker = balance.tokenName.toUpperCase() as Ticker
      if (Object.values(Ticker).includes(ticker)) {
        setSwapModalState({
          isOpen: true,
          fromTicker: ticker,
          availableAmount: balance.amount,
        })
      }
    }
  }

  const handleSendClick = (balance: Balance) => {
    if (balance.tokenName && balance.amount) {
      // Convert tokenName to Ticker enum
      const ticker = balance.tokenName.toUpperCase() as Ticker
      if (Object.values(Ticker).includes(ticker)) {
        setSendTokenModalState({
          isOpen: true,
          fromTicker: ticker,
          availableAmount: balance.amount,
        })
      }
    }
  }

  const closeSwapModal = () => {
    setSwapModalState({
      isOpen: false,
      fromTicker: null,
      availableAmount: 0,
    })
  }

  const closeSendTokenModal = () => {
    setSendTokenModalState({
      isOpen: false,
      fromTicker: null,
      availableAmount: 0,
    })
  }

  const columns = [
    {
      Header: 'Chain',
      accessor: 'chain.name',
      disableFilters: true,
      disableSortBy: true,
    },
    {
      Filter: SelectColumnFilter,
      Header: 'Assets',
      accessor: 'tokenName',
      disableFilters: true,
      disableSortBy: true,
    },
    {
      Cell: ({ cell }: any) => (
        <>
          <div className="tooltip" data-tip={cell.row.tokenName}>
            {cell.row.values.amount.toFixed(4)}
          </div>
        </>
      ),
      Header: 'Quantity',
      accessor: 'amount',
      disableFilters: true,
    },
    {
      Cell: ({ cell }: any) => <>{cell.row.values.value.toFixed(2)} $</>,
      Header: 'USD',
      accessor: 'value',
      disableFilters: true,
      disableSortBy: true,
    },
    {
      Cell: ({ cell }: any) => <> {cell.row.values.price} $</>,
      Header: 'Price',
      accessor: 'price',
      disableFilters: true,
    },
    {
      Cell: ({ cell }: any) => {
        const balance = cell.row.original as Balance
        
        return (
          <div className="flex justify-center gap-1">
            {balance.tokenName && balance.amount && balance.amount > 0 && Object.values(Ticker).includes(balance.tokenName.toUpperCase() as Ticker) && (
              <>
                <button
                  className="btn btn-xs btn-outline btn-info"
                  onClick={() => handleSwapClick(balance)}
                  title={`Swap ${balance.tokenName}`}
                >
                  <FiRefreshCw className="h-3 w-3" />
                  <span className="ml-1">Swap</span>
                </button>
                <button
                  className="btn btn-xs btn-outline btn-success"
                  onClick={() => handleSendClick(balance)}
                  title={`Send ${balance.tokenName}`}
                >
                  <FiSend className="h-3 w-3" />
                  <span className="ml-1">Send</span>
                </button>
              </>
            )}
          </div>
        )
      },
      Header: 'Actions',
      accessor: 'actions',
      disableFilters: true,
      disableSortBy: true,
    },
  ]

  return (
    <>
      <Table
        columns={columns}
        data={balances}
        showTotal={showTotal}
        showPagination={false}
      />
      
      {swapModalState.isOpen && swapModalState.fromTicker && (
        <SwapModal
          isOpen={swapModalState.isOpen}
          onClose={closeSwapModal}
          account={account}
          fromTicker={swapModalState.fromTicker}
          availableAmount={swapModalState.availableAmount}
        />
      )}

      {sendTokenModalState.isOpen && sendTokenModalState.fromTicker && (
        <SendTokenModal
          isOpen={sendTokenModalState.isOpen}
          onClose={closeSendTokenModal}
          account={account}
          fromTicker={sendTokenModalState.fromTicker}
          availableAmount={sendTokenModalState.availableAmount}
        />
      )}
    </>
  )
}

export default AccountRowDetails
