import Spinner from '@/components/Spinner';
import { AiContent } from './useAiImageQueries';
import { HiSparkles } from 'react-icons/hi';
import { ALL_AI_AUTO_GENERATED_FIELDS, AiAutoGeneratedField } from '.';
import { useMemo } from 'react';
import { clsx } from 'clsx/lite';

export default function AiButton({
  aiContent,
  requestFields = ALL_AI_AUTO_GENERATED_FIELDS,
  shouldConfirm,
  className,
}: {
  aiContent: AiContent
  requestFields?: AiAutoGeneratedField[]
  shouldConfirm?: boolean
  className?: string
}) {
  const isLoading = useMemo(() =>
    (requestFields ?? []).map(field => {
      switch (field) {
      case 'title':
        return aiContent.isLoadingTitle;
      case 'caption':
        return aiContent.isLoadingCaption;
      case 'tags':
        return aiContent.isLoadingTags;
      case 'semantic':
        return aiContent.isLoadingSemantic;
      default:
        return false;
      }
    }).some(Boolean)
  , [
    requestFields,
    aiContent.isLoadingCaption,
    aiContent.isLoadingSemantic,
    aiContent.isLoadingTags,
    aiContent.isLoadingTitle,
  ]);

  return (
    <button
      className={clsx(
        'flex min-w-[3.25rem] min-h-9 justify-center',
        className,
      )}
      onClick={e => {
        if (
          !shouldConfirm ||
          confirm('Are you sure you want to overwrite existing content?')
        ) {
          aiContent.request(requestFields);
        } else {
          e.preventDefault();
        }
      }}
      disabled={!aiContent.isReady || isLoading}
    >
      {isLoading ? <Spinner /> : <HiSparkles size={16} />}
    </button>
  );
}
