import { useState, useEffect } from 'react'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { ConnectedUserMenu } from './ConnectedUserMenu'
import { CreateAccountModal } from './CreateAccountModal'
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, showCreateModal: boolean, showUnlockModal: boolean, connect: () => Promise<void>) {
  useEffect(() => {
    if (accountExists === true && !pubkey && !showCreateModal && !showUnlockModal) {
      void connect()
    }
  }, [accountExists, pubkey, showCreateModal, 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 DisconnectedModals({
  showCreateModal,
  showUnlockModal,
  setShowCreateModal,
  setShowUnlockModal,
}: {
  showCreateModal: boolean
  showUnlockModal: boolean
  setShowCreateModal: (show: boolean) => void
  setShowUnlockModal: (show: boolean) => void
}) {
  return (
    <>
      {showCreateModal && (
        <CreateAccountModal
          onSuccess={() => {
            setShowCreateModal(false)
            setShowUnlockModal(true)
          }}
          onClose={() => setShowCreateModal(false)}
        />
      )}
      {showUnlockModal && (
        <UnlockAccountModal
          onSuccess={() => setShowUnlockModal(false)}
          onClose={() => setShowUnlockModal(false)}
        />
      )}
    </>
  )
}

function DisconnectedState({
  loading,
  error,
  showCreateModal,
  showUnlockModal,
  setShowCreateModal,
  setShowUnlockModal,
}: {
  loading: boolean
  error: string | null
  showCreateModal: boolean
  showUnlockModal: boolean
  setShowCreateModal: (show: boolean) => void
  setShowUnlockModal: (show: boolean) => void
}) {
  return (
    <>
      <ConnectForm
        onCreateAccount={() => setShowCreateModal(true)}
        onUnlock={() => setShowUnlockModal(true)}
        loading={loading}
        error={error}
      />
      <DisconnectedModals
        showCreateModal={showCreateModal}
        showUnlockModal={showUnlockModal}
        setShowCreateModal={setShowCreateModal}
        setShowUnlockModal={setShowUnlockModal}
      />
    </>
  )
}

export function ConnectButton() {
  const { connected, pubkey, profile, loading, error, connect, disconnect, accountExists, isUnlocked } = useNostrAuth()
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showUnlockModal, setShowUnlockModal] = useState(false)

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

  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}
      error={error}
      showCreateModal={showCreateModal}
      showUnlockModal={showUnlockModal}
      setShowCreateModal={setShowCreateModal}
      setShowUnlockModal={setShowUnlockModal}
    />
  )
}
