'use client';

import React from 'react';

import { useTranslations } from 'next-intl';

import { FaHourglassHalf } from 'react-icons/fa';
import { FaRegFilePdf } from 'react-icons/fa6';

import { Button, type ButtonProps } from '@/components/ui/button';

type PdfButtonProps = Omit<ButtonProps, 'children'> & {
  generatingLabel?: string;
  isGenerating?: boolean;
  label?: string;
  showIcon?: boolean;
};

const PdfButton = React.forwardRef<HTMLButtonElement, PdfButtonProps>(
  (
    {
      className,
      disabled,
      generatingLabel,
      isGenerating = false,
      label,
      showIcon = true,
      size = label ? 'sm' : 'icon',
      title,
      variant = 'outline',
      'aria-label': ariaLabel,
      ...props
    },
    ref
  ) => {
    const t = useTranslations('common');
    const downloadLabel = t('downloadPdf');
    const loadingLabel = generatingLabel ?? t('generatePdf');
    const visibleLabel = isGenerating && generatingLabel ? generatingLabel : label;
    const accessibleLabel = ariaLabel ?? (isGenerating ? loadingLabel : (label ?? downloadLabel));

    return (
      <Button
        ref={ref}
        type="button"
        variant={variant}
        size={size}
        disabled={disabled || isGenerating}
        aria-busy={isGenerating || undefined}
        aria-label={accessibleLabel}
        className={className}
        title={title ?? accessibleLabel}
        {...props}
      >
        {visibleLabel && <span>{visibleLabel}</span>}

        {showIcon &&
          (isGenerating ? (
            <FaHourglassHalf aria-hidden="true" className="animate-spin" />
          ) : (
            <FaRegFilePdf aria-hidden="true" />
          ))}
      </Button>
    );
  }
);

PdfButton.displayName = 'PdfButton';

export default PdfButton;
