// File input styled as a dropzone — Task 10. Used for both QuickBooks
// uploads (Account Listing, Journal). Plain <input type="file"> under the
// hood (click-to-browse always works) with drag-and-drop layered on top;
// no dependency added, just DOM drag events.
//
// `accept` (Bank Rec Task 4) defaults to ".xlsx" so every existing caller
// (the setup wizard's two QuickBooks uploads) is unaffected — the statement
// import wizard is the first caller to pass its own (".csv,.ofx,.qfx"). Note
// the browser's `accept` attribute is only a picker HINT, never enforced for
// drag-and-drop — callers that care about rejecting the wrong file type
// (the import wizard does) must still check the extension themselves in
// onFileSelected, same as this component's own header always implied for
// click-to-browse.

import { useCallback, useRef, useState } from "react";

export function Dropzone({
  label,
  hint,
  accept = ".xlsx",
  selectedFileName,
  disabled,
  onFileSelected,
}: {
  label: string;
  hint?: string;
  accept?: string;
  selectedFileName?: string | null;
  disabled?: boolean;
  onFileSelected: (file: File) => void;
}) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [dragOver, setDragOver] = useState(false);

  const pick = useCallback(() => {
    if (!disabled) inputRef.current?.click();
  }, [disabled]);

  const handleFiles = useCallback(
    (files: FileList | null) => {
      const file = files?.[0];
      if (file) onFileSelected(file);
    },
    [onFileSelected],
  );

  return (
    <div
      className={`dropzone${dragOver ? " dropzone-active" : ""}${disabled ? " dropzone-disabled" : ""}`}
      role="button"
      tabIndex={disabled ? -1 : 0}
      aria-disabled={disabled}
      onClick={pick}
      onKeyDown={(ev) => {
        if (ev.key === "Enter" || ev.key === " ") {
          ev.preventDefault();
          pick();
        }
      }}
      onDragOver={(ev) => {
        ev.preventDefault();
        if (!disabled) setDragOver(true);
      }}
      onDragLeave={() => setDragOver(false)}
      onDrop={(ev) => {
        ev.preventDefault();
        setDragOver(false);
        if (!disabled) handleFiles(ev.dataTransfer.files);
      }}
    >
      <input
        ref={inputRef}
        type="file"
        accept={accept}
        style={{ display: "none" }}
        disabled={disabled}
        onChange={(ev) => handleFiles(ev.target.files)}
      />
      <div className="dropzone-label">{label}</div>
      {hint && <div className="dropzone-hint">{hint}</div>}
      <div className="dropzone-file">
        {selectedFileName ? `Selected: ${selectedFileName}` : "Click to choose a file, or drag one here"}
      </div>
    </div>
  );
}
