import React, {useState} from 'react'
import {FiRefreshCw, FiSend} from 'react-icons/fi'
import {useQuery} from '@tanstack/react-query'

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

interface IAccountRowDetailProps extends IAccountRowDetail {
  account: Account
}

const AccountRowDetails: React.FC<IAccountRowDetailProps> = ({
  balances,
  showTotal,
  account,
}) => {
  const { apiUrl } = useApiUrlStore()
  const accountClient = new AccountClient({}, apiUrl)

  // Fetch exchange approval status using TanStack Query
  const { data: exchangeApprovalStatus, isLoading: isLoadingApprovalStatus, error: approvalStatusError, refetch: refetchApprovalStatus } = useQuery({
    queryKey: ['exchangeApprovalStatus'],
    queryFn: async () => {
      return await accountClient.account_GetExchangeApprovalStatus()
    },
    staleTime: 60000, // Consider data fresh for 1 minute
    gcTime: 5 * 60 * 1000, // Keep in cache for 5 minutes
    retry: 2, // Retry failed requests up to 2 times
    enabled: !!apiUrl, // Only run query when apiUrl is available
  })

  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}
      />

      {/* Exchange Approval Status */}
      <div className="mt-4">
        <div className="flex items-center justify-between mb-2">
          <h4 className="text-sm font-medium text-gray-700">Exchange Approval Status</h4>
          <button
            className={`btn btn-xs btn-ghost ${isLoadingApprovalStatus ? 'loading' : ''}`}
            onClick={() => refetchApprovalStatus()}
            disabled={isLoadingApprovalStatus}
            title="Refresh approval status"
          >
            {!isLoadingApprovalStatus && <FiRefreshCw className="h-3 w-3" />}
            {!isLoadingApprovalStatus && <span className="ml-1">Refresh</span>}
          </button>
        </div>
        {isLoadingApprovalStatus ? (
          <div className="text-sm text-gray-500">Loading approval status...</div>
        ) : approvalStatusError ? (
          <div className="text-sm text-red-500">Error loading approval status</div>
        ) : exchangeApprovalStatus && exchangeApprovalStatus.length > 0 ? (
          <div className="flex flex-wrap gap-2">
            {exchangeApprovalStatus.map((status) => (
              <div
                key={status.exchange}
                className={`badge ${
                  status.isInitialized 
                    ? 'badge-success' 
                    : 'badge-outline'
                }`}
              >
                {status.exchange}: {status.isInitialized ? 'Initialized' : 'Not Initialized'}
              </div>
            ))}
          </div>
        ) : (
          <div className="text-sm text-gray-500">No exchange data available</div>
        )}
      </div>
      
      {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
