import React, { HTMLProps, useContext, useRef, useState } from "react";
import classNames from "classnames";
import { bem } from "../../utilities/bem";
import { Button, BUTTON_VARIANT } from "../Button";
import { FormGroupContext } from "../FormGroup/FormGroupContext";
import { Text } from "../Text";
import { Truncate } from "../Truncate";

const cn = "FileUpload";

export interface FileUploadProps extends React.HTMLProps<HTMLLabelElement> {
  inputProps: HTMLProps<HTMLInputElement>;
  label?: string;
}

// @Deprecated
// This version of the FileUpload component will be removed in arrow-ds v2.
// The FileUploadDnD component then be renamed FileUpload.
export const FileUpload = ({
  className,
  inputProps = {},
  label = "Select file",
  ...rest
}: FileUploadProps) => {
  const inputRef = useRef<HTMLInputElement>(null);

  const { id: idProp, onChange, ...inputRest } = inputProps;
  const { id: idContext } = useContext(FormGroupContext);
  const id = idContext || idProp;

  const emptyText = "No file chosen";
  const [fileLabel, setFileLabel] = useState(emptyText);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const inputElement = inputRef.current;
    const files = inputElement && inputElement.files;

    if (inputElement) {
      if (!files) {
        setFileLabel(emptyText);
      } else if (files.length > 1) {
        setFileLabel(`${files.length} files`);
      } else {
        const filePath = event.target.value;
        const fileName = filePath.split("\\").pop();
        if (fileName) {
          setFileLabel(fileName);
        }
      }

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

  return (
    <label htmlFor={id} className={classNames(bem(cn), className)} {...rest}>
      <input
        className={classNames(bem(cn, { e: "input" }))}
        ref={inputRef}
        type="file"
        id={id}
        onChange={handleChange}
        {...inputRest}
      />
      <Button
        className={classNames(bem(cn, { e: "button" }))}
        as="div"
        variant={BUTTON_VARIANT.SECONDARY}
      >
        {label}
      </Button>
      <Truncate>
        <Text className={classNames(bem(cn, { e: "fileLabel" }))}>
          {fileLabel}
        </Text>
      </Truncate>
    </label>
  );
};
