import React, { ReactNode, useState } from 'react';
import { IconType, NotificationBanner } from '@nova-hf/ui';
import { MainButtonProps } from '@nova-hf/ui/umd/ts/src/buttons/MainButton/MainButton';
import { MainColorType, SecondaryColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';

const findTextInArray = (stringArray: string[], counter: number) => {
  const lastIndex = stringArray.length - 1;
  if (counter > lastIndex) {
    return stringArray[lastIndex];
  } else {
    return stringArray[counter];
  }
};

type ErrorBannerProps = {
  titles: string[];
  descriptions: string[];
  eyebrowTexts: string[];
  icon: IconType;
  color: MainColorType | SecondaryColorType;
  refetchButton?: Omit<MainButtonProps, 'colorScheme'>;
  contactButton?: MainButtonProps;
  showLoading?: boolean;
  loadingComponent: ReactNode;
  hasPingAlert?: boolean;
};

export const ErrorBanner = ({
  titles,
  descriptions,
  eyebrowTexts,
  icon,
  color,
  refetchButton,
  contactButton,
  showLoading,
  loadingComponent,
  hasPingAlert,
}: ErrorBannerProps) => {
  const [countRefetch, setCountRefetch] = useState(0);

  const handleRefetch = () => {
    if (refetchButton?.onClick) {
      setCountRefetch((counter) => counter + 1);
      refetchButton.onClick();
    }
  };

  return (
    <>
      {showLoading ? (
        loadingComponent
      ) : (
        <NotificationBanner
          hasPingAlert={!!hasPingAlert}
          title={findTextInArray(titles, countRefetch)}
          description={findTextInArray(descriptions, countRefetch)}
          eyebrowText={findTextInArray(eyebrowTexts, countRefetch)}
          icon={icon}
          color={color}
          {...(refetchButton && {
            mainButtonColored: {
              text: refetchButton.text,
              icon: refetchButton.icon,
              onClick: () => handleRefetch(),
              isLoading: showLoading,
              colorScheme: color,
            },
          })}
          {...(contactButton && {
            mainButtonWhite: { ...contactButton },
          })}
        />
      )}
    </>
  );
};
