import { useState, useRef } from 'react';
import { DownloadFile } from '../../../../models/Applio/Files';
import './PdfUploader.scss';
import download from '../../../../assets/images/arrows-2-download-manager.svg'

const MAX_FILE_SIZE = 4096 * 1024;



export type FileUploaderProps = {
  label?: string;
  fieldName: string;
  existingFile?: DownloadFile | null;
  onFileChange?: (fieldName: string, file: File) => void;
  onDownload?: (file: DownloadFile) => Promise<void>;
  hasError?: string;
  id?: string;
};

const ACCEPTED_MIME_TYPES = [
  'application/pdf',
  // 'application/msword',
  // 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  // 'application/zip',
  // 'application/x-zip-compressed',
  // 'application/vnd.rar',
  // 'application/x-rar-compressed',
];

const ACCEPTED_EXTENSIONS = '.pdf,.doc,.docx,.zip,.rar';

function isAccepted(file: File) {
  return ACCEPTED_MIME_TYPES.includes(file.type) && file.size <= MAX_FILE_SIZE;
}

const FileUploader = ({
  label,
  fieldName,
  existingFile,
  onFileChange,
  onDownload,
  hasError,
  id,
}: FileUploaderProps) => {
  const [isDragging, setIsDragging] = useState(false);
  const [stagedFile, setStagedFile] = useState<File | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const displayName = stagedFile?.name ?? existingFile?.originalFilename ?? '';
  const hasFile = !!displayName;

  const handleFile = (file: File) => {
    if (!isAccepted(file)) return;
    setStagedFile(file);
    onFileChange?.(fieldName, file);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) handleFile(file);
    if (inputRef.current) inputRef.current.value = '';
  };

  const openFilePicker = () => {
    inputRef.current?.click();
  };

  return (
    <>
      <input
        ref={inputRef}
        type="file"
        id={id ?? fieldName}
        accept={ACCEPTED_EXTENSIONS}
        style={{ display: 'none' }}
        onChange={handleInputChange}
      />

      <div
        className={[
          'drag-drop-uploader',
          isDragging ? 'dragging' : '',
          hasFile ? 'light-blue-border' : 'blue-border',
        ]
          .filter(Boolean)
          .join(' ')}
        onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
        onDragLeave={() => setIsDragging(false)}
        onDrop={handleDrop}
        onClick={openFilePicker}
      >
        <div className="file-info">
          {!hasFile ? (
            <p className="uploader-label">PLEASE UPLOAD: {label}</p>
          ) : (
            <p className="file-name">{displayName}</p>
          )}
        </div>

        {hasFile && (
          <div className="actions" onClick={(e) => e.stopPropagation()}>
            {/* Download — only for server-side files, not yet-to-be-uploaded staged files */}
            {!stagedFile && existingFile && onDownload && (
              <button
                type="button"
                className="download-btn"
                onClick={() => onDownload(existingFile)}
              >
                <img src={download}/>
              </button>
            )}
          </div>
        )}
      </div>
      <div>{hasError && <p style={{ color: 'red', fontSize: '1.2rem', marginTop: 6 }}>{hasError}</p>}</div>
    </>
  );
};

export default FileUploader;
