import { useCallback, useEffect, useState } from 'react';
import { useMatrixClient } from './useMatrixClient';
import { useUserTrustStatusChange } from './useUserTrustStatusChange';
import { useCrossSigningActive } from './useCrossSigning';

export type UserVerifiedStatus = 'verified' | 'unverified' | 'unknown';

export function useUserVerifiedStatus(userId: string): UserVerifiedStatus {
  const mx = useMatrixClient();
  const crossSigningActive = useCrossSigningActive();
  const [status, setStatus] = useState<UserVerifiedStatus>('unknown');

  const check = useCallback(async () => {
    const crypto = mx.getCrypto();
    if (!crypto || !crossSigningActive) {
      setStatus('unknown');
      return;
    }
    try {
      const vs = await crypto.getUserVerificationStatus(userId);
      setStatus(vs.isVerified() ? 'verified' : 'unverified');
    } catch {
      setStatus('unknown');
    }
  }, [mx, userId, crossSigningActive]);

  useEffect(() => {
    check();
  }, [check]);

  useUserTrustStatusChange(
    useCallback(
      (changedUserId: string) => {
        if (changedUserId === userId) check();
      },
      [userId, check],
    ),
  );

  return status;
}
