import { useNavigate } from 'react-router-dom';
import { useIdentity } from '../hooks/useIdentity';
import { isPairingSatisfied } from '../utils/pairing';
import { getStoredRelays } from '../utils/relay';

export function HomeScreen(): JSX.Element {
  const navigate = useNavigate();
  const { identity, isLoading } = useIdentity();
  const pairingSatisfied = isPairingSatisfied();
  const relays = getStoredRelays();
  const relayStatus = relays.length > 0 ? 'OK' : 'Non configuré';

  if (isLoading) {
    return (
      <div role="status" aria-live="polite" aria-busy="true">
        Chargement...
      </div>
    );
  }

  if (identity === null) {
    return (
      <main>
        <h1>UserWallet Login</h1>
        <p>Identité locale absente</p>
        <div>
          <button onClick={() => navigate('/create-identity')}>
            Créer une identité locale
          </button>
          <button onClick={() => navigate('/import-identity')}>
            Importer une identité
          </button>
        </div>
      </main>
    );
  }

  return (
    <main>
      <h1>UserWallet Login</h1>
      <section aria-labelledby="identity-status">
        <h2 id="identity-status">Statut identité</h2>
        <p>
          <strong>Présente:</strong> Oui
        </p>
        <p>
          <strong>Clé publique:</strong>{' '}
          <code>{identity.publicKey.slice(0, 16)}...</code>
        </p>
        {identity.name !== undefined && (
          <p>
            <strong>Nom:</strong> {identity.name}
          </p>
        )}
      </section>
      <section aria-labelledby="pairing-status">
        <h2 id="pairing-status">Statut pairing</h2>
        <p>
          <strong>Requis:</strong> Oui
        </p>
        <p>
          <strong>Satisfait:</strong> {pairingSatisfied ? 'Oui' : 'Non'}
        </p>
        {!pairingSatisfied && (
          <p role="alert">
            ⚠️ Pairing obligatoire avant de pouvoir se connecter
          </p>
        )}
      </section>
      <section aria-labelledby="network-status">
        <h2 id="network-status">Statut réseau relais</h2>
        <p>
          <strong>Statut:</strong> {relayStatus}
        </p>
        {relays.length > 0 && (
          <p>
            <strong>Nombre de relais:</strong> {relays.length}
          </p>
        )}
      </section>
      <section aria-labelledby="actions">
        <h2 id="actions">Actions</h2>
        <div>
          <button onClick={() => navigate('/login')} disabled={!pairingSatisfied}>
            Se connecter
          </button>
          <button onClick={() => navigate('/manage-pairs')}>Gérer les pairs</button>
          <button onClick={() => navigate('/relay-settings')}>
            Réglages relais
          </button>
          <button onClick={() => navigate('/sync')}>Synchroniser maintenant</button>
          <button onClick={() => navigate('/services')}>Services disponibles</button>
        </div>
      </section>
    </main>
  );
}
