import React from 'react';
import { Checkbox } from '@patternfly/react-core';
import { useFormikContext } from 'formik';
import { ClusterCreateParams } from '@openshift-assisted/types/assisted-installer-service';
import { PullSecretField, PullSecretInfo } from '../ui';
import { useTranslation } from '../../hooks/use-translation-wrapper';

export type PullSecretProps = {
  defaultPullSecret?: string;
  isOcm?: boolean;
  isSingleClusterFeatureEnabled?: boolean;
};

const PullSecret: React.FC<PullSecretProps> = ({
  defaultPullSecret,
  isOcm = false,
  isSingleClusterFeatureEnabled = false,
}) => {
  const [isExpanded, setExpanded] = React.useState(!defaultPullSecret);
  const { setFieldValue } = useFormikContext<ClusterCreateParams>();
  const { t } = useTranslation();
  if (isOcm || isSingleClusterFeatureEnabled) {
    const onCheckboxChange = () => {
      if (isExpanded) {
        // about to collapse, reset to original value
        setFieldValue('pullSecret', defaultPullSecret);
      }
      setExpanded(!isExpanded);
    };

    return (
      <>
        <Checkbox
          id="checkbox-pull-secret"
          className="pf-v6-u-display-inline-flex"
          aria-label={t('ai:edit pull secret')}
          isChecked={isExpanded}
          onChange={onCheckboxChange}
          label={
            <>
              {t('ai:Edit pull secret')} <PullSecretInfo isOcm={isOcm} />
            </>
          }
        />
        {isExpanded && <PullSecretField isOcm={isOcm} />}
      </>
    );
  }

  return <PullSecretField isOcm={isOcm} />;
};

export default PullSecret;
