import { useState, useEffect } from 'react'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { ConnectedUserMenu } from './ConnectedUserMenu'
import { RecoveryStep } from './CreateAccountModalSteps'
import { UnlockAccountModal } from './UnlockAccountModal'
import type { NostrProfile } from '@/types/nostr'

function ConnectForm({
  onCreateAccount,
  onUnlock,
  loading,
  error,
}: {
  onCreateAccount: () => void
  onUnlock: () => void
  loading: boolean
  error: string | null
}) {
  return (
    <div className="flex flex-col gap-2">
      <button
        onClick={onCreateAccount}
        disabled={loading}
        className="px-6 py-2 bg-neon-cyan/20 hover:bg-neon-cyan/30 text-neon-cyan rounded-lg font-medium transition-all border border-neon-cyan/50 hover:shadow-glow-cyan disabled:opacity-50"
      >
        Créer un compte
      </button>
      <button
        onClick={onUnlock}
        disabled={loading}
        className="px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors disabled:opacity-50"
      >
        Se connecter
      </button>
      {error && <p className="text-sm text-red-400">{error}</p>}
    </div>
  )
}

function useAutoConnect(accountExists: boolean | null, pubkey: string | null, showRecoveryStep: boolean, showUnlockModal: boolean, connect: () => Promise<void>) {
  useEffect(() => {
    if (accountExists === true && !pubkey && !showRecoveryStep && !showUnlockModal) {
      void connect()
    }
  }, [accountExists, pubkey, showRecoveryStep, showUnlockModal, connect])
}

function ConnectedState({ pubkey, profile, loading, disconnect }: { pubkey: string; profile: NostrProfile | null; loading: boolean; disconnect: () => Promise<void> }) {
  return (
    <ConnectedUserMenu
      pubkey={pubkey}
      profile={profile}
      onDisconnect={() => {
        void disconnect()
      }}
      loading={loading}
    />
  )
}

function UnlockState({ loading, error, onUnlock, onClose }: { loading: boolean; error: string | null; onUnlock: () => void; onClose: () => void }) {
  return (
    <>
      <ConnectForm
        onCreateAccount={() => {}}
        onUnlock={onUnlock}
        loading={loading}
        error={error}
      />
      <UnlockAccountModal onSuccess={onClose} onClose={onClose} />
    </>
  )
}


function DisconnectedState({
  loading,
  error,
  showUnlockModal,
  setShowUnlockModal,
  onCreateAccount,
}: {
  loading: boolean
  error: string | null
  showUnlockModal: boolean
  setShowUnlockModal: (show: boolean) => void
  onCreateAccount: () => void
}) {
  return (
    <>
      <ConnectForm
        onCreateAccount={onCreateAccount}
        onUnlock={() => setShowUnlockModal(true)}
        loading={loading}
        error={error}
      />
      {showUnlockModal && (
        <UnlockAccountModal
          onSuccess={() => setShowUnlockModal(false)}
          onClose={() => setShowUnlockModal(false)}
        />
      )}
    </>
  )
}

export function ConnectButton() {
  const { connected, pubkey, profile, loading, error, connect, disconnect, accountExists, isUnlocked } = useNostrAuth()
  const [showRecoveryStep, setShowRecoveryStep] = useState(false)
  const [showUnlockModal, setShowUnlockModal] = useState(false)
  const [recoveryPhrase, setRecoveryPhrase] = useState<string[]>([])
  const [npub, setNpub] = useState('')
  const [creatingAccount, setCreatingAccount] = useState(false)
  const [createError, setCreateError] = useState<string | null>(null)

  useAutoConnect(accountExists, pubkey, false, showUnlockModal, connect)

  const handleCreateAccount = async () => {
    setCreatingAccount(true)
    setCreateError(null)
    try {
      const { nostrAuthService } = await import('@/lib/nostrAuth')
      const result = await nostrAuthService.createAccount()
      setRecoveryPhrase(result.recoveryPhrase)
      setNpub(result.npub)
      setShowRecoveryStep(true)
    } catch (e) {
      setCreateError(e instanceof Error ? e.message : 'Failed to create account')
    } finally {
      setCreatingAccount(false)
    }
  }

  const handleRecoveryContinue = () => {
    setShowRecoveryStep(false)
    setShowUnlockModal(true)
  }

  const handleUnlockSuccess = () => {
    setShowUnlockModal(false)
    setRecoveryPhrase([])
    setNpub('')
  }

  if (connected && pubkey && isUnlocked) {
    return <ConnectedState pubkey={pubkey} profile={profile} loading={loading} disconnect={disconnect} />
  }

  if (accountExists === true && pubkey && !isUnlocked && !showUnlockModal && !showCreateModal) {
    return (
      <UnlockState
        loading={loading}
        error={error}
        onUnlock={() => setShowUnlockModal(true)}
        onClose={() => setShowUnlockModal(false)}
      />
    )
  }

  return (
    <>
      <DisconnectedState
        loading={loading || creatingAccount}
        error={error || createError}
        showUnlockModal={showUnlockModal}
        setShowUnlockModal={setShowUnlockModal}
        onCreateAccount={handleCreateAccount}
      />
      {showRecoveryStep && (
        <RecoveryStep
          recoveryPhrase={recoveryPhrase}
          npub={npub}
          onContinue={handleRecoveryContinue}
        />
      )}
      {showUnlockModal && (
        <UnlockAccountModal
          onSuccess={handleUnlockSuccess}
          onClose={() => setShowUnlockModal(false)}
        />
      )}
    </>
  )
}
