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

export type UserDevice = {
  deviceId: string;
  displayName?: string;
};

export type UserDevicesState =
  | { status: 'loading' }
  | { status: 'error' }
  | { status: 'success'; devices: UserDevice[] };

export function useOtherUserDevices(userId: string): UserDevicesState {
  const mx = useMatrixClient();
  const crossSigningActive = useCrossSigningActive();
  const [state, setState] = useState<UserDevicesState>({ status: 'loading' });

  const fetchDevices = useCallback(async () => {
    const crypto = mx.getCrypto();
    if (!crypto || !crossSigningActive) {
      setState({ status: 'success', devices: [] });
      return;
    }
    setState({ status: 'loading' });
    try {
      const deviceMap = await crypto.getUserDeviceInfo([userId], true);
      const userDevices = deviceMap.get(userId);
      setState({
        status: 'success',
        devices: userDevices
          ? Array.from(userDevices.values()).map((device) => ({
              deviceId: device.deviceId,
              displayName: device.displayName,
            }))
          : [],
      });
    } catch {
      setState({ status: 'error' });
    }
  }, [mx, userId, crossSigningActive]);

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

  useDeviceListChange(
    useCallback(
      (userIds: string[]) => {
        if (userIds.includes(userId)) fetchDevices();
      },
      [userId, fetchDevices],
    ),
  );

  return state;
}
