import {provider, setProvider} from "@/blockchain/provider.js";
import {BrowserProvider, ethers} from "ethers";
import {useStore} from "@/store/store";
import {errorSuggestsMissingVault, SingletonCoroutine} from "@/misc.js";
import {newContract, vaultAddress, vaultContract} from "@/blockchain/contract.js";
import {defineStore} from "pinia";
import {computed, ref} from "vue";
import {metadataMap, version} from "@/version.js";
import {TransactionState, TransactionType} from "@/blockchain/transactionDecl.js";
import {track} from "@/track.js";
import {socket} from "@/socket.js";
import {web3modal} from "@/blockchain/web3modal.js";


export const useWalletStore = defineStore('wallet', ()=>{
  // this is what the wallet is logged into.  it could be different than the application's store.chainId.
  const chainId = ref(0)

  // OLD Pending Order Format
  // {
  //   chainId: 31337,  // must never be null, even if no wallet plugin exists.  chosen by app, not wallet.
  //   placementTime: Date.now(),
  //   state: PendingOrderState.Submitted
  //   tx: null  // transaction ID
  //   vault: '0x...',  // or null if account not logged in yet
  //   order: {tokenIn:..., tokenOut:..., ...} // blockchain binary order object
  // }
  const pendingOrders = ref([])

  // NEW Format is a single Transaction class
  const _tx = ref(null)
  const transaction = computed({
    get() {return _tx.value},
    set(v) {
      _tx.value = v;
      if (v===null) {
        console.log('clear transaction')
        if (progressionInvoker!==null) {
          clearTimeout(progressionInvoker)
          progressionInvoker = null
        }
      }
      else {
        console.log('set transaction', v)
        transactionProgressor.invoke();
        if (progressionInvoker===null)
          progressionInvoker = setInterval(()=>transactionProgressor.invoke(), 1000)
      }
    },
  })

  return {
    chainId, pendingOrders, transaction,
  }
})


export function onChainChanged(chainId) {
  console.log('onChainChanged', chainId)
  chainId = Number(chainId)
  socket.emit('chain', chainId)
  const store = useStore()
  const ws = useWalletStore()
  if( chainId !== ws.chainId ) {
    console.log('wallet chain changed', chainId)
    ws.chainId = chainId
    if (chainId.toString() in metadataMap) {
      console.log('app chain changed', chainId)
      store.chainId = chainId
      store.account = null
      setProvider(new BrowserProvider(window.ethereum, chainId))
      updateAccounts(chainId, provider)
    }
    else {
      console.log('app chain NOT changed')
    }
  }
}


export function updateAccounts(chainId, provider) {
  provider.listAccounts().then((accounts) => changeAccounts(chainId, accounts.map((a) => a.address)))
}


function changeAccounts(chainId, accounts) {
  // this is a notification from the wallet that the user selected a different blockchain.  that chain may or may not
  // be supported.
  console.log('changeAccounts', chainId, accounts)
  const store = useStore()
  if (chainId === store.chainId && accounts.length) {
    const addr = accounts[0]
    if (addr !== store.account) {
      console.log('account logged in', addr)
      track('login', {chainId, address: addr})
      store.account = addr
      store.vaults = []
      // one of these two methods will call flushTransactions()
      if (useWalletStore().transaction!==null)
        ensureVault()
      else
        discoverVaults(addr)
      socket.emit('address', chainId, addr)
    }
  }
  else {
    console.log('account logged out')
    store.account = null
    store.vaults = []
  }
}

function onAccountsChanged(accounts) {
  console.log('onAccountsChanged', accounts)
  const store = useStore()
  const ws = useWalletStore()
  if (accounts.length === 0 || accounts[0] !== store.account)
    changeAccounts(ws.chainId, accounts);
}

export function detectChain() {
  try {
    window.ethereum.on('chainChanged', onChainChanged);
    window.ethereum.on('accountsChanged', onAccountsChanged);
    new ethers.BrowserProvider(window.ethereum).getNetwork().then((network)=>{
      const chainId = network.chainId
      onChainChanged(chainId)
    })
  }
  catch (e) {
    console.log('Could not connect change hooks to wallet', e)
  }
}

// Commented out - Web3Modal handles wallet detection now
// detectChain()

const errorHandlingProxy = {
  get(target, prop, proxy) {
    const got = Reflect.get(target, prop, proxy);
    if( typeof got !== 'function' ) {
      return got
    }
    else {
      return async function (...args) {
        try {
          return await got.apply(target, args)
        }
        catch (x) {
          target._connected(false)
          target._enabled = false
          if( x.code === 'NETWORK_ERROR' ) {
            // todo available chain names
            // store.error('Wrong Blockchain', 'Your wallet is connected to a different blockchain. Please select Arbitrum in your wallet.') // todo hardcoded arb
            console.error('wallet chain error', x)
            // store.chainId = store.chainInfo[]
            throw x
          }
          else {
            console.error('wallet error')
            throw x
          }
        }
      }
    }
  }
}


export async function connectWallet(chainId) {
  console.log('connectWallet via Web3Modal', chainId)

  // Return a promise that resolves when connection is complete
  return new Promise((resolve, reject) => {
    let resolved = false
    let unsubscribeProvider = null
    let unsubscribeState = null

    // Subscribe to provider changes (fires when wallet connects)
    unsubscribeProvider = web3modal.subscribeProvider(async (newState) => {
      console.log('Provider state changed:', newState)

      if (newState.provider && !resolved) {
        resolved = true
        unsubscribeProvider?.()
        unsubscribeState?.()

        try {
          const walletProvider = newState.provider

          // Create ethers provider from Web3Modal provider
          const p = new BrowserProvider(walletProvider)
          setProvider(p)

          // Get network info from the provider
          const network = await p.getNetwork()
          const connectedChainId = Number(network.chainId)

          console.log('Connected to chain', connectedChainId)

          // Update wallet store
          const ws = useWalletStore()
          ws.chainId = connectedChainId

          // Get accounts
          await updateAccounts(connectedChainId, p)

          // Subscribe to Web3Modal provider events
          subscribeToProviderEvents(walletProvider)

          resolve()
        } catch (e) {
          console.error('Error after connection', e)
          reject(e)
        }
      }
    })

    // Subscribe to modal state (fires when modal opens/closes)
    unsubscribeState = web3modal.subscribeState((state) => {
      // If modal closes without connection, resolve the promise
      if (state.open === false && !resolved) {
        console.log('Modal closed without connection')
        resolved = true
        unsubscribeProvider?.()
        unsubscribeState?.()
        resolve() // Resolve (not reject) so the button re-enables
      }
    })

    // Open the modal
    web3modal.open().catch((e) => {
      if (!resolved) {
        resolved = true
        unsubscribeProvider?.()
        unsubscribeState?.()

        if (e.reason === 'rejected' || e.message?.includes('rejected')) {
          const ws = useWalletStore();
          const tx = ws.transaction
          if (tx) {
            tx.state = TransactionState.Rejected
            ws.transaction = null
          }
          resolve() // Don't reject on user cancellation
        } else {
          reject(e)
        }
      }
    })

    // Timeout after 60 seconds
    setTimeout(() => {
      if (!resolved) {
        resolved = true
        unsubscribeProvider?.()
        unsubscribeState?.()
        console.log('Connection timeout')
        resolve() // Resolve instead of reject so button re-enables
      }
    }, 60000)
  })
}

// Subscribe to provider events from Web3Modal
function subscribeToProviderEvents(walletProvider) {
  // Handle account changes
  walletProvider.on('accountsChanged', (accounts) => {
    console.log('accountsChanged from Web3Modal', accounts)
    if (accounts.length === 0) {
      disconnectWallet()
    } else {
      onAccountsChanged(accounts)
    }
  })

  // Handle chain changes
  walletProvider.on('chainChanged', (chainId) => {
    console.log('chainChanged from Web3Modal', chainId)
    onChainChanged(chainId)
  })

  // Handle disconnect
  walletProvider.on('disconnect', () => {
    console.log('Provider disconnected from Web3Modal')
    disconnectWallet()
  })
}


function discoverVaults(owner) {
  const s = useStore()
  console.log('discoverVaults', owner)
  if( owner === null )
    s.vaults = []
  else
    doDiscoverVaults.invoke(owner)
}

const doDiscoverVaults = new SingletonCoroutine(_discoverVaults, 50)

async function _discoverVaults(owner) {
  const result = []
  const versions = []
  const s = useStore()
  if( !owner || !s.chainId || !s.account) {
    s.vaults = []
    return
  }
  // todo multi-vault scan
  // console.log('_discoverVaults',owner)
  for (let num=0; num < 1; num++) {
    const num = 0
    const addr = vaultAddress(s.factory, s.vaultInitCodeHash, owner, num)
    // console.log(`vault ${num} at`, addr)
    if (addr === null)  // no more vaults
      break
    if (!provider) {
      console.log('No provider')
      return  // do not change whatever was already found
    }
    const vault = await vaultContract(addr, provider)
    try {
      const version = Number(await vault.version())
      console.log(`found vault #${num} v${version} at ${addr}`)
      result.push(addr)
      versions.push(version)
    } catch (e) {
      if (errorSuggestsMissingVault(e))
        console.log(`no vault ${num} at ${addr}`)
      else
        console.error(`discoverVaults failed`, e)
      return  // do not change what was already found todo is this correct?
    }
  }
  console.log('new account === owner?', s.account, owner)
  if( s.account === owner ) { // double-check the account since it could have changed during our await
    s.vaults = result
    s.vaultVersions = versions
    if( useWalletStore().transaction ) {
      const num = 0 // todo multiple vaults
      if (result.length)
        flushWalletTransactions(s.chainId, owner, num, result[0])
      else
        ensureVault2(s.chainId, owner, num)
    }
  }
}


export function ensureVault() {
  ensureVaultFunc.invoke()
}


const ensureVaultFunc = new SingletonCoroutine(ensureVault1,1)


async function ensureVault1() {
  const s = useStore()
  const owner = s.account;
  if (owner===null)
    await connectWallet(s.chainId)
  ensureVault2(s.chainId, owner, 0)
}

export function ensureVault2(chainId, owner, num) {
  console.log('ensureVault2', chainId, owner, num)
  if( !chainId ) {
    console.log('cannot create vault: no chain selected')
    return
  }
  if( !owner ) {
    console.log('cannot create vault: no account logged in')
    return
  }
  ensureVaultRoutine.invoke(chainId, owner, num)
}

async function doEnsureVault(chainId, owner, num) {
  const s = useStore();
  if (s.vaults.length <= num)
    await _discoverVaults(owner)
  if( s.vaults[num] )
    flushWalletTransactions(chainId, owner, num, s.vaults[num])
  else {
    console.log(`requesting vault ${owner} ${num}`)
    socket.emit('ensureVault', chainId, owner, num)
  }
}

const ensureVaultRoutine = new SingletonCoroutine(doEnsureVault, 100)


export async function cancelOrder(vault, orderIndex) {
  console.log('cancel order', vault, orderIndex)
  pendTransaction(async (signer)=> {
    const contract = await vaultContract(vault, signer)
    if( contract === null ) {
      console.error('vault contract was null while canceling order', vault, orderIndex)
      return null
    }
    return await contract.cancelDexorder(orderIndex)
  })
}

async function progressTransactions() {
  const s = useStore()
  const ws = useWalletStore();
  console.log('progressTransactions', ws.transaction)
  if( ws.transaction===null )
    return
  if( s.account === null ) {
    let signer = null
    try {
      console.log('account is null. requesting sign-in.')
      signer = await provider.getSigner()
    }
    catch (e) {
      console.log('signer error', e.code, e.info?.error?.code)
      if (e?.info?.error?.code === 4001) {
        console.log('signer rejected')
        signer = null
      }
      else
        throw e
    }
    if (signer === null) {
        console.log('setting tx state to rejected')
        ws.transaction.state = TransactionState.Rejected
        ws.transaction = null
        return
    }
  }
  if( s.vault === null ) {
    console.log('vault is null. requesting vault creation.')
    ensureVault()
    return
  }
  if( ws.transaction.state < TransactionState.Proposed )
    ws.transaction.propose(s.account, s.vault)
  if( ws.transaction.type === TransactionType.PlaceOrder ) {
    flushWalletTransactions(s.chainId, s.account, 0, s.vault)
  }
  else {
    console.log('flushing transaction', ws.transaction.type)
    if (ws.transaction.state < TransactionState.Proposed) {
      pendTransaction(async (signer) => {
        if (signer.address !== ws.transaction.owner) {
          console.error('signer address does not match transaction owner', signer.address, ws.transaction.owner)
          return
        }
        const contract = await vaultContract(ws.transaction.vault, signer)
        return await ws.transaction.createTx(contract)
      })
    }
  }
}

const transactionProgressor = new SingletonCoroutine(progressTransactions, 10)

let progressionInvoker = null


export function flushWalletTransactions(chainId, owner, num, vault) {
  const ws = useWalletStore();
  console.log('flushWalletTransactions', chainId, owner, num, vault)
  let needsFlush = ws.transaction !== null && ws.transaction.type !== TransactionType.PlaceOrder
  for( const pend of ws.pendingOrders ) {
    if (pend.vault === null)
      pend.vault = vault
    if (pend.state === PendingOrderState.Submitted) {
      console.log('flushing order', pend.id)
      pendOrderAsTransaction(pend)
      setPendState(pend, PendingOrderState.Signing)
      needsFlush = true
    }
  }
  if (needsFlush)
    flushTransactions()
}


function pendOrderAsTransaction(pend) {
  pendTransaction(async (signer)=> {
    // console.log('pendTransaction')
    let contract
    try {
      contract = await vaultContract(pend.vault, signer)
    }
    catch (e) {
      console.error('vault contract was null while sending order transaction', pend.vault)
      return null
    }
    try {
      await switchChain(pend.chainId)
    }
    catch (e) {
      if(e.code===4001) {
        console.log('user refused chain switch')
        setPendState(pend, PendingOrderState.Rejected)
        return null
      }
      else {
        console.error('Unknown error while switching chain to pend order', e)
        return null
      }
    }
    if (pend.fee === null) {
      const [orderFee, gasFee] = await placementFee(pend.vault, pend.order)
      pend.fee = orderFee + gasFee
    }
    console.log('placing order', pend.id, pend.fee, pend.order)
    const tx = await contract.placeDexorder(pend.order, {value:pend.fee})
    pend.tx = tx
    setPendState(pend, PendingOrderState.Sent)
    console.log(`order ${pend.id} sent transaction`, tx)
    tx.wait().then((txReceipt)=>{
      console.log('mined order', pend.id, txReceipt)
      pend.receipt = txReceipt
      const ws = useWalletStore();
      ws.pendingOrders = ws.pendingOrders.filter((p)=>p!==pend)  // remove pend since order was mined
    })
    return tx
  },
  (e) => {
    if( e.info?.error?.code === 4001 ) {
      console.log(`wallet refused order`, pend.id)
      setPendState(pend, PendingOrderState.Rejected)
      return true  // returning true means we handled the error.  any other return value will dump to console.
    }
  })
}


export function pendTransaction(sender, errHandler) {
  console.log('pendTransaction')
  const s = useStore()
  s.transactionSenders.push([sender,errHandler])
  flushTransactions()
}


const flushTransactionsRoutine = new SingletonCoroutine(asyncFlushTransactions,1)

export function flushTransactions() {
  flushTransactionsRoutine.invoke()
}

async function asyncFlushTransactions() {
  const s = useStore()
  const ws = useWalletStore()
  console.log('flushTransactions', ws.transaction, s.vault)
  if (ws.transaction !== null) {
    if (s.vault === null) {
      console.log('transaction doesn\'t have a vault. creating one.')
      await ensureVault()
      if (s.vault === null) {
        console.error('vault could not be created')
        const tx = ws.transaction
        if (tx) {
          tx.state = TransactionState.Error
          ws.transaction = null
        }
        return
      }
    }
  }
  if( provider === null ) {
    console.log('warning: asyncFlushOrders() cancelled due to null provider')
    return
  }
  const senders = s.transactionSenders
  if (!senders.length) {
    console.log('no transactionSenders!')
    return
  }
  console.log(`flushing ${senders.length} transactions`)
  let signer
  try {
    signer = await provider.getSigner();
  } catch (e) {
    // {
    //     "code": -32002,
    //     "message": "Already processing eth_requestAccounts. Please wait."
    // }
    console.log('signer denied')
    return
  }
  for (const [sender,errHandler] of senders)
    doSendTransaction(sender, signer, errHandler)
  s.transactionSenders = []
}

function doSendTransaction(sender, signer, errHandler) {
  const s = useStore();
  s.removeTransactionSender(sender)
  sender(signer).then((tx)=>{
    if (tx!==null) {
      console.log('sent transaction', tx)
      tx.wait().then((tr)=>{
        console.log('tx receipt',tr)
      })
    }
  }).catch(async (e)=>{
    let dumpErr = true
    if (errHandler!==undefined)
      dumpErr = await errHandler(e) !== true
    if (dumpErr) {
      if( e.reason && e.info )
        console.error('error sending transaction', e.reason, e.info)
      else
        console.error('error sending transaction', e)
    }
  })
}


export async function detectUpgrade() {
  if (!provider) {
    console.log('no provider!')
    return null
  }
  const s = useStore()
  if (!s.vault) {
    console.log('no vault logged in')
    return null
  }

  const info = version.chainInfo[s.chainId]
  if (!info) {
    console.log(`couldn't get chainInfo for ${s.chainId}`)
    return null
  }
  try {
    console.log('factory', info.factory)
    const [factory, vault] = await Promise.all([
        newContract(info.factory, 'IVaultFactory', provider),
        newContract(s.vault, 'IVault', provider),
    ])
    const vaultImpl = await vault.implementation()
    const latestImpl = await factory.implementation()
    console.log('vaultImpl / latestImpl', vaultImpl, latestImpl)
    if ( vaultImpl !== latestImpl ) {
      s.upgrade = latestImpl
      const impl = await newContract(latestImpl, 'IVault', provider)
      const version = await impl.version()
      console.log(`found vault version ${version}`)
      return version
    }
  }
  catch (e) {
    console.log('ignorable error while querying for an upgrade', e)
  }
  return null
}


function upgradeSender(vault, impl) {
  return async function (signer) {
    const v = await vaultContract(vault, signer)
    v.upgrade(impl)
  }
}


function upgradeError(e) {
  console.error('error while upgrading vault', e)
}


export async function upgradeVault(vault, impl) {
  pendTransaction(upgradeSender(vault, impl), upgradeError)
}


const _chainInfos = {
  // Arbitrum One
  42161: {
    "chainId": "0xa4b1",
    "chainName": "Arbitrum One",
    "rpcUrls": ["https://arbitrum-mainnet.infura.io"],
    "blockExplorerUrls": ['https://explorer.arbitrum.io'],
    "nativeCurrency": {
      "name": "Ethereum",
      "symbol": "ETH",
      "decimals": 18
    }
  },
  1337: {
    "chainId": "0x539",
    "chainName": "Dexorder Alpha Testnet",
    "rpcUrls": ["https://rpc.alpha.dexorder.com"],
    "nativeCurrency": {
      "name": "Test Ethereum",
      "symbol": "TETH",
      "decimals": 18
    }
  },
  31337: {
    "chainId": "0x7a69",
    "chainName": "Mockchain",
    "rpcUrls": ["http://localhost:8545"],
    "nativeCurrency": {
      "name": "Test Ethereum",
      "symbol": "TETH",
      "decimals": 18
    }
  },
}


export async function switchChain(chainId) {
  if (useWalletStore().chainId === chainId)
    return
  await window.ethereum.request({
    "method": "wallet_switchEthereumChain",
    "params": [{"chainId": '0x' + chainId.toString(16)}]
  })
}


export async function addNetwork(chainId) {
  const info = _chainInfos[chainId]
  if (!info) {
    console.log(`No info to add chain ${chainId}`)
    return
  }
  await window.ethereum.request({
    "method": "wallet_addEthereumChain",
    "params": [info]
  });
}

export async function addNetworkAndConnectWallet(chainId) {

    try {
        await connectWallet(chainId)
    } catch (e) {
        if (e.code !== 4001)
            console.log('connectWallet() failed', e)
    }
}

export async function disconnectWallet() {
  console.log('disconnectWallet')
  const store = useStore()
  const ws = useWalletStore()

  // Disconnect from Web3Modal
  try {
    await web3modal.disconnect()
  } catch (e) {
    console.log('Web3Modal disconnect error (ignoring)', e)
  }

  // Clear provider
  setProvider(null)

  // Clear account and vaults
  store.account = null
  store.vaults = []
  store.vaultVersions = []

  // Clear any pending transactions
  if (ws.transaction !== null) {
    ws.transaction = null
  }
  ws.pendingOrders = []

  // Clear transaction senders
  store.transactionSenders = []

  // Emit socket disconnect
  socket.emit('address', ws.chainId, null)

  track('logout', {chainId: ws.chainId})
  console.log('Wallet disconnected')
}

// Make it globally accessible from console
if (typeof window !== 'undefined') {
  window.disconnectWallet = disconnectWallet
}
