import React, { useState } from 'react';
import { Loader2, FileDown } from 'lucide-react';
import { format } from 'date-fns';

export function CustomFormPdfExportButton({ onClick, isLoading, formName, className = '' }) {
  const [isHovered, setIsHovered] = useState(false);

  const getFilename = () => {
    const safeName = (formName || 'form').replace(/[^a-z0-9]/gi, '_').toLowerCase();
    const date = format(new Date(), 'yyyy-MM-dd');
    return `${safeName}-${date}`;
  };

  const handleClick = async () => {
    if (!onClick) return;
    try {
      await onClick(getFilename());
    } catch (error) {
      console.error('ExportButton: Export failed', error);
    }
  };

  return (
    <button
      onClick={handleClick}
      disabled={isLoading}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      title="Generate and download PDF report"
      className={[
        'inline-flex items-center justify-center gap-2 h-8 px-4 text-xs font-medium rounded-lg',
        'border border-slate-200 bg-white hover:bg-slate-50 text-slate-700',
        'transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed',
        'min-w-[140px]',
        className,
      ].join(' ')}
    >
      {isLoading ? (
        <>
          <Loader2 className="w-4 h-4 animate-spin" />
          Exporting...
        </>
      ) : (
        <>
          <FileDown className={`w-4 h-4 ${isHovered ? 'animate-bounce' : ''}`} />
          Export PDF
        </>
      )}
    </button>
  );
}

export default CustomFormPdfExportButton;
