import clsx from 'clsx';
import Image from 'next/image';
import { useRef, useState } from 'react';
import style from './index.module.scss';

interface FileUploaderProps {
  onFileSelect: (file: File) => void;
}

const FileUploader: React.FC<FileUploaderProps> = ({ onFileSelect }) => {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [fileName, setFileName] = useState<string | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];
      onFileSelect(file);

      const isImage = file.type.startsWith('image/');
      setFileName(file.name);

      if (isImage) {
        const url = URL.createObjectURL(file);
        setPreviewUrl(url);
      } else {
        setPreviewUrl(null);
      }
    }
  };

  return (
    <div
      className={clsx(
        style.fileUploader,
        'd-flex mt-3 flex-column justify-content-center align-items-center'
      )}
      onClick={() => inputRef.current?.click()}
      style={{ cursor: 'pointer' }}
    >
      {previewUrl ? (
        <Image
          src={previewUrl}
          alt="Preview"
          width={80}
          height={80}
          style={{ objectFit: 'cover', borderRadius: 8 }}
        />
      ) : (
        <Image
          width={40}
          height={40}
          src={'/images/icons/uploader-icon.png'}
          alt="Upload"
        />
      )}

      <p className={`text-light-grey-2 ${style.uploadText}`}>
        {fileName
          ? fileName
          : 'Upload an image of the delivered item or the related invoice.'}
      </p>

      <input
        ref={inputRef}
        type="file"
        accept="image/*,.pdf,.doc,.docx"
        onChange={handleFileChange}
        style={{ display: 'none' }}
      />
    </div>
  );
};

export default FileUploader;
