import browser from 'webextension-polyfill'
import React, { useState, useContext, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import hideStringMiddle from '../helpers/hideStringMiddle'
import ImportAccountModal from '../modals/ImportAccountModal'
import DeriveAccountModal from '../modals/DeriveAccountModal'
import MainContext from '../contexts/MainContext'
import { getSessionVault, setSessionVault } from '../common'

const Accounts = () => {
  const { accounts, defaultAccount, updateDefaultAccount } = useContext(MainContext)

  const [isDropdownOpen, setIsDropdownOpen] = useState(false)
  const [showImportAccountModal, setShowImportAccountModal] = useState(false)
  const [showDeriveAccount, setShowDeriveAccount] = useState(false)

  const dropdownRef = useRef(null)
  const navigate = useNavigate()

  // Close dropdown on click outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsDropdownOpen(false)
      }
    }

    const handleEscape = (event) => {
      if (event.key === 'Escape') {
        setIsDropdownOpen(false)
      }
    }

    if (isDropdownOpen) {
      document.addEventListener('mousedown', handleClickOutside)
      document.addEventListener('keydown', handleEscape)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
      document.removeEventListener('keydown', handleEscape)
    }
  }, [isDropdownOpen])

  const changeDefaultAccount = async (prvKey) => {
    const vault = await getSessionVault()
    if (!vault) return

    // Find the account being switched to
    const targetAccount = accounts.find(acc => acc.prvKey === prvKey)
    const accountName = targetAccount?.name ||
      (targetAccount?.type === 'derived' ? `Account ${targetAccount.index}` : `Imported ${targetAccount?.index}`)

    vault.accountDefault = prvKey

    // Encrypt via background (key stays in background memory)
    const response = await browser.runtime.sendMessage({
      type: 'ENCRYPT_VAULT',
      data: vault
    })

    if (response.success) {
      await browser.storage.local.set({ encryptedVault: response.encryptedData })
    }

    await setSessionVault(vault)
    await updateDefaultAccount()
    setIsDropdownOpen(false)

    // Show confirmation toast
    toast.success(`Switched to ${accountName}`, {
      position: 'bottom-center',
      autoClose: 2000,
      hideProgressBar: true
    })

    navigate('/vault')
  }

  const toggleDropdown = () => {
    setIsDropdownOpen(prev => !prev)
  }

  const lockVault = async () => {
    // Send lock request to background (clears key from memory)
    await browser.runtime.sendMessage({ type: 'LOCK_VAULT' })
  }

  return (
    <>
      <div className="account" ref={dropdownRef}>
        <a href="#" className="account-profile" onClick={(e) => { e.preventDefault(); toggleDropdown() }}>
          <span className={`account-profile__arrow ${isDropdownOpen ? 'open' : ''}`}>&#x25BC;</span>
          <img className="account-profile__img" src={defaultAccount.picture} alt="" />
          <div className="account-profile__body">
            <strong className="account-profile__name">
              {!defaultAccount.type
                ? 'Loading...'
                : defaultAccount.type === "derived"
                  ? (defaultAccount.name || `Account ${defaultAccount.index}`)
                  : (defaultAccount.name || `Imported ${defaultAccount.index}`)}
            </strong>
          </div>
        </a>

        {isDropdownOpen && (
          <div className="account-dropdown">
            <div className="account-dropdown__head">
              <div>
                <div className="account-dropdown__title">Accounts</div>
              </div>
              <a href="#" onClick={(e) => { e.preventDefault(); lockVault() }} title="Lock now">
                <i className="icon-lock"></i> Lock
              </a>
            </div>

            <div className="account-items">
              {accounts.length === 0 ? (
                <div className="account-items__loading">
                  Loading accounts...
                </div>
              ) : accounts.map((account) => {
                const isCurrentAccount = account.prvKey === defaultAccount.prvKey
                const displayName = account.type === "derived"
                  ? (account.name || `Account ${account.index}`)
                  : (account.name || `Imported ${account.index}`)
                return (
                  <div
                    key={account.prvKey}
                    className={`account-dropdown__item ${isCurrentAccount ? 'current' : ''}`}
                  >
                    <a href="#" onClick={(e) => { e.preventDefault(); changeDefaultAccount(account.prvKey) }}>
                      <div className={`account-dropdown__avatar ${isCurrentAccount ? 'current' : ''}`}>
                        <img src={account.picture} alt="" />
                        {isCurrentAccount && (
                          <span className="account-dropdown__badge">✓</span>
                        )}
                      </div>
                      <div className="account-dropdown__info">
                        <div className="account-dropdown__name-row">
                          <strong className="account-dropdown__name">
                            {displayName}
                          </strong>
                          {account.type === "derived" && <small className="account-dropdown__tag">Derived</small>}
                          {account.type === "imported" && <small className="account-dropdown__tag">Imported</small>}
                        </div>
                        <div className="account-dropdown__npub">
                          {account.npub ? hideStringMiddle(account.npub, 8, 6) : '...'}
                        </div>
                      </div>
                    </a>
                  </div>
                )
              })}
            </div>

            <ul className="account-dropdown-nav">
              <li>
                <a href="#" onClick={(e) => { e.preventDefault(); setShowDeriveAccount(true); setIsDropdownOpen(false) }} title="Derive account">
                  <i className="icon-user-plus"></i> Derive account
                </a>
              </li>
              <li>
                <a href="#" onClick={(e) => { e.preventDefault(); setShowImportAccountModal(true); setIsDropdownOpen(false) }} title="Import account">
                  <i className="icon-download"></i> Import account
                </a>
              </li>
            </ul>
          </div>
        )}

        <ImportAccountModal
          isOpen={showImportAccountModal}
          callBack={() => setShowImportAccountModal(false)}
          onClose={() => setShowImportAccountModal(false)}
        />

        <DeriveAccountModal
          isOpen={showDeriveAccount}
          callBack={() => setShowDeriveAccount(false)}
          onClose={() => setShowDeriveAccount(false)}
        />
      </div>
    </>
  )
}

export default Accounts
