import { type FC, useRef } from 'react';

import Input from '@material-hu/mui/Input';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';

type Props = {
  title: string;
  icon: any;
  onChange?: (files: File[]) => void;
  onClick?: () => void;
  inputProps?: any;
};

const FileInputMenuItem: FC<Props> = ({
  title,
  icon,
  onChange,
  inputProps,
  onClick,
}) => {
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const theme = useTheme();

  const handleAttach = (): void => {
    fileInputRef.current?.click();
    onClick && onClick();
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const inputFiles = event.target.files;
    const files = [];

    if (inputFiles) {
      for (let i = 0; i < inputFiles.length; i++) {
        files.push(inputFiles[i]);
      }
    }

    onChange?.(files);

    // Reset the file input value to allow re-selection of the same file
    event.target.value = '';
  };

  return (
    <HuMenuItem onClick={handleAttach}>
      <Stack sx={{ flexDirection: 'row', gap: 1, alignItems: 'center' }}>
        <Stack
          sx={{
            backgroundColor: theme.palette.new.background.elements.brand,
            borderRadius: '50%',
            height: 40,
            width: 40,
            justifyContent: 'center',
            alignItems: 'center',
            flexShrink: 0,
            color: theme.palette.new.text.neutral.brand,
            '& svg': { color: theme.palette.new.text.neutral.brand },
          }}
        >
          {icon}
        </Stack>
        <Typography
          variant="globalS"
          sx={{ fontWeight: 600 }}
        >
          {title}
        </Typography>
        <Input
          type="file"
          sx={{ display: 'none' }}
          inputRef={fileInputRef}
          onChange={handleChange}
          inputProps={inputProps}
        />
      </Stack>
    </HuMenuItem>
  );
};

export default FileInputMenuItem;
