"use client";

import { Input } from "@/app/shadcn_components/ui/input";

export function InputFile({
  onFileSelect,
  isValidating,
  isValid,
  errorMessage,
}: {
  onFileSelect: (file: File) => void;
  isValidating: boolean;
  isValid: boolean | null;
  errorMessage: string | null;
}) {
  function handleOnChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    const validExtensions = ["csv", "xls", "xlsx"];
    const fileExtension = file.name.split(".").pop()?.toLowerCase();

    if (!fileExtension || !validExtensions.includes(fileExtension)) {
      console.error("Unsupported file type");
      e.target.value = "";
      return;
    }

    onFileSelect(file);
  }

  return (
    <div className="grid w-full max-w-sm items-center gap-1.5 text-sm font-semibold text-gray-600">
      <Input
        id="csv-uploader"
        type="file"
        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        onChange={handleOnChange}
        disabled={isValidating}
        className={`cursor-pointer ${isValidating ? "opacity-50" : ""}`}
      />

      {isValidating && (
        <span className="text-sm text-gray-500 mt-1">Validating file…</span>
      )}

      {isValid === false && !isValidating && (
        <span className="text-sm text-red-500 mt-1">{errorMessage}</span>
      )}
    </div>
  );
}
