import { useMemo } from 'react';
import { useEffectOnce } from 'react-use';

import { type AzureCredentials, AzureCloud, updateDatasourceCredentials } from '@grafana/azure-sdk';
import { type SelectableValue } from '@grafana/data';
import { config } from '@grafana/runtime';
import { type HttpSettingsBaseProps } from '@grafana/ui/internal';

import { getCredentials } from './AzureCredentialsConfig';
import { AzureCredentialsForm } from './AzureCredentialsForm';

export const KnownAzureClouds: Array<SelectableValue<AzureCloud>> = [{ value: AzureCloud.Public, label: 'Azure' }];

export const AzureAuthSettings = (props: HttpSettingsBaseProps) => {
  const { dataSourceConfig: dsSettings, onChange } = props;
  const managedIdentityEnabled = config.azure.managedIdentityEnabled;
  const azureEntraPasswordCredentialsEnabled = config.azure.azureEntraPasswordCredentialsEnabled;
  const userIdentityEnabled = config.azure.userIdentityEnabled;

  const credentials = useMemo(() => getCredentials(dsSettings), [dsSettings]);

  const onCredentialsChange = (credentials: AzureCredentials): void => {
    onChange(updateDatasourceCredentials(dsSettings, credentials));
  };

  // The auth type needs to be set on the first load of the data source
  useEffectOnce(() => {
    if (!dsSettings.jsonData.authType) {
      onCredentialsChange(credentials);
    }
  });

  return (
    <AzureCredentialsForm
      managedIdentityEnabled={managedIdentityEnabled}
      azureEntraPasswordCredentialsEnabled={azureEntraPasswordCredentialsEnabled}
      userIdentityEnabled={userIdentityEnabled}
      credentials={credentials}
      azureCloudOptions={KnownAzureClouds}
      onCredentialsChange={onCredentialsChange}
      disabled={dsSettings.readOnly}
    />
  );
};

export default AzureAuthSettings;
