import React, { forwardRef, ReactNode, useRef, useCallback, ChangeEvent } from 'react';
import styles from './FileInputLink.module.css';
import { useDispatch } from '../../app/store';
import { loadUrl } from './fileSlice';

type Props = {
  children?: ReactNode;
} & React.DetailedHTMLProps<
  React.InputHTMLAttributes<HTMLInputElement>,
  HTMLInputElement
>;

let idCounter = 0;

export const FileInputLink = forwardRef<HTMLInputElement, Props>(
  function FileInputLink({ children, onChange: onChangeProp, ...props }, ref) {
    const idRef = useRef<string>();
    if (idRef.current === undefined) {
      idRef.current = `${styles.fileInput}--${idCounter++}`;
    }

    const dispatch = useDispatch();
    const onChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {
      if (event.target.files?.length === 1) {
        window.history.pushState(
          window.history.state,
          document.title,
          window.location.href
        );
        dispatch(loadUrl(URL.createObjectURL(event.target.files[0])));
      }
      if (onChangeProp) {
        onChangeProp(event);
      }
    }, [dispatch, onChangeProp]);

    const id = idRef.current;
    return (
      <>
        <input
          type="file"
          id={id}
          className={styles.fileInput}
          ref={ref}
          accept=".raw,.txt,text/plain"
          {...props}
          onChange={onChange}
        />
        <label htmlFor={id} className={styles.link}>
          {children}
        </label>
      </>
    );
  }
);
