import { Box, Button, Spinner, Text, color } from 'folds';
import React, { useCallback } from 'react';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { startOidcLogin } from '../oidc/oidcLoginUtil';

type OidcLoginProps = {
  issuer: string;
  homeserverBaseUrl: string;
  serverName: string;
};
/**
 * Native next-gen-auth (MSC3861/MSC2965) login button. Discovers + registers
 * with the homeserver's OIDC provider and redirects to it. Mirrors `SSOLogin`'s
 * single-button styling.
 */
export function OidcLogin({ issuer, homeserverBaseUrl, serverName }: OidcLoginProps) {
  const [state, startLogin] = useAsyncCallback<void, unknown, Parameters<typeof startOidcLogin>>(
    useCallback(startOidcLogin, []),
  );

  // Loading = discovering/registering; Success = redirect issued (page is leaving) —
  // keep the button busy in both cases.
  const ongoing = state.status === AsyncStatus.Loading || state.status === AsyncStatus.Success;

  return (
    <Box direction="Column" gap="300">
      {state.status === AsyncStatus.Error && (
        <Text size="T200" align="Center" style={{ color: color.Critical.Main }}>
          Failed to start single sign-on. Please try again.
        </Text>
      )}
      <Button
        style={{ width: '100%' }}
        size="500"
        variant="Secondary"
        fill="Soft"
        outlined
        onClick={() => startLogin(issuer, homeserverBaseUrl)}
        disabled={ongoing}
        before={ongoing ? <Spinner size="200" variant="Secondary" /> : undefined}
      >
        <Text align="Center" size="B500" truncate>
          {`Continue with ${serverName}`}
        </Text>
      </Button>
    </Box>
  );
}
