import cn from "classnames";
import React, { useCallback } from "react";
import PropTypes from "prop-types";
import { IFileProps } from "./form.d";
import Form from "./form-tags";

const File = (props: IFileProps) => {
  const {
    className,
    disabled,
    error,
    fileLabel,
    help,
    label,
    labelClassName,
    name,
    onBlur,
    onChange,
    placeholder,
    required,
    value,
    escapeHelpContent
  } = props;
  const testId = props["data-testid"] || "honeyui-file";

  const onChangeCallback = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      onChange(e);
    },
    [onChange]
  );

  const onBlurCallback = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      onBlur && onBlur(e);
    },
    [onBlur]
  );

  return (
    <Form.Group>
      <Form.LabelTag className={labelClassName} name={name} data-testid={`${testId}-label`}>
        {label}
      </Form.LabelTag>
      <div
        className={cn("input-group", {
          "is-invalid": !!error
        })}
      >
        <div className="custom-file">
          <input
            className={cn("custom-file-input", className, {
              "is-invalid": !!error
            })}
            data-testid={testId}
            disabled={disabled}
            id={name}
            name={name}
            onBlur={onBlurCallback}
            onChange={onChangeCallback}
            placeholder={placeholder}
            required={required}
            type="file"
          />
          <Form.LabelTag
            className="custom-file-label d-flex"
            data-testid={`${testId}-label`}
            name={name}
          >
            <span className="w-75 text-truncate">{value || fileLabel}</span>
          </Form.LabelTag>
        </div>
      </div>
      <Form.HelpTag data-testid={`${testId}-help`} name={name} escapeContent={escapeHelpContent}>
        {help}
      </Form.HelpTag>
      <Form.ErrorTag data-testid={`${testId}-error`} name={name}>
        {error}
      </Form.ErrorTag>
    </Form.Group>
  );
};

File.displayName = "File";

File.propTypes = {
  className: PropTypes.string,
  disabled: PropTypes.bool,
  error: PropTypes.string,
  fileLabel: PropTypes.string,
  help: PropTypes.string,
  label: PropTypes.string,
  labelClassName: PropTypes.string,
  name: PropTypes.string.isRequired,
  onBlur: PropTypes.func,
  onChange: PropTypes.func.isRequired,
  placeholder: PropTypes.string,
  required: PropTypes.bool,
  escapeHelpContent: PropTypes.bool
};

File.defaultProps = {
  disabled: false,
  // TODO: use i18n text
  fileLabel: "Choose file",
  required: false
};

export default File;
