import { useState } from 'react';
import { forwardRef } from 'react';
import { FileInputProps } from '@theme/components/types';
import { useLocalization } from '@akinon/next/hooks';
import { twMerge } from 'tailwind-merge';

export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(
  function FileInput(
    {
      buttonClassName,
      onChange,
      fileClassName,
      fileNameWrapperClassName,
      fileInputClassName,
      ...props
    },
    ref
  ) {
    const { t } = useLocalization();
    const [fileNames, setFileNames] = useState<string[]>([]);

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
      const files = Array.from(event.target.files || []);
      setFileNames(files.map((file) => file.name));

      if (onChange) {
        onChange(event);
      }
    };

    return (
      <div className="relative">
        <input
          type="file"
          {...props}
          ref={ref}
          className={twMerge(
            'absolute inset-0 w-full h-full opacity-0 cursor-pointer',
            fileInputClassName
          )}
          onChange={handleFileChange}
        />
        <button
          type="button"
          className={twMerge(
            'bg-primary text-white py-2 px-4 text-sm',
            buttonClassName
          )}
        >
          {t('common.file_input.select_file')}
        </button>
        <div
          className={twMerge('mt-1 text-gray-500', fileNameWrapperClassName)}
        >
          {fileNames.length > 0 ? (
            <ul className={twMerge('list-disc pl-4 text-xs', fileClassName)}>
              {fileNames.map((name, index) => (
                <li key={index}>{name}</li>
              ))}
            </ul>
          ) : (
            <span className={twMerge('text-xs', fileClassName)}>
              {t('common.file_input.no_file')}
            </span>
          )}
        </div>
      </div>
    );
  }
);
