// resources\assets\ts\share\aufgaben-shared\components\Comments.tsx
// original: resources\assets\ts\DataPage\Comments.tsx
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Fab from '@mui/material/Fab';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import { Comment } from '~t/share/Comments';
import { Trans } from '@lingui/macro';
import {
  addComment,
  addCommentFile,
  deleteComment,
  openUploadDialog,
} from '../slices/commentsSlice';
import { useDispatch } from 'react-redux';
import AttachFileIcon from '@mui/icons-material/AttachFile';
import CommentTable from '~t/share/Comments';
import React from 'react';

interface CommentsProps {
  comments: Comment[];
  ergID: number;
  fetchComment: (number) => any;
  canDelete: boolean;
}



export default function Comments({
  comments,
  ergID,
  canDelete,
}: CommentsProps) {
  const d = useDispatch();
  const formRef = React.useRef<HTMLFormElement>(null);
  const textFieldRef = React.useRef<HTMLInputElement>(null); //tried this for solving comment input not disappearing
  const [isSubmitting, setIsSubmitting] = React.useState(false);  //add this to solve unintended multiple submissions 

  const handleFileUploadClick = () => {
    d(openUploadDialog(ergID));
  };

  function handleCommentDelete(sak_id) {
    d(deleteComment({ sak_id, erg_id: ergID }));
  }

  return (
    <Paper>
      <Box p={1}>
        <Typography variant='h6'>
          <Trans>Comments</Trans>
        </Typography>

        {comments.length > 0 && (
          <Box>
            <CommentTable
              comments={comments}
              handleDelete={handleCommentDelete}
              canDelete={canDelete}
            />
          </Box>
        )}
        <Box>
          <form
            ref={formRef}
            onSubmit={(e) => {
              e.preventDefault();

             
              if (isSubmitting) return;

              const file = (e.target as any).commentfile.files[0];
              if (file !== undefined) {
                setIsSubmitting(true); 
                d(addCommentFile({ ergID, file }))
                  .then(() => {
                    formRef.current?.reset();
                    textFieldRef.current?.blur();
                  })
                  .finally(() => {
                    setIsSubmitting(false); 
                  });
                return;
              }

              const commentStr = (e.target as any).commenttext.value;
              if (commentStr !== '') {
                setIsSubmitting(true); 
                d(addComment({ comment: commentStr, ergID }))
                  .then(() => {
                    formRef.current?.reset();
                    textFieldRef.current?.blur();
                  })
                  .finally(() => {
                    setIsSubmitting(false); 
                  });
              }
            }}
          >
            <Grid container alignItems='center'>
              <Grid size ={10}>
                <TextField
                  fullWidth
                  label={<Trans>Comment</Trans>}
                  name='commenttext'
                  inputRef={textFieldRef}
                  disabled={isSubmitting} 
                />
              </Grid>

              <Grid size="grow">
                <input
                  id={'icon-button-file'}
                  type='file'
                  style={{ display: 'none' }}
                  name='commentfile'
                  onChange={(e) => {
                    e.preventDefault();
                    
                    
                    if (isSubmitting) return;
                    
                    const file = (e.target as any).files[0];
                    if (file !== undefined) {
                      setIsSubmitting(true);
                      d(addCommentFile({ ergID, file }))
                        .then(() => {
                          formRef.current?.reset();
                          textFieldRef.current?.blur();
                        })
                        .finally(() => {
                          setIsSubmitting(false);
                        });
                    }
                  }}
                />
              </Grid>

              <Grid size="grow">
                <Button 
                  type='submit'
                  disabled={isSubmitting} 
                >
                  <Trans>Submit</Trans>
                </Button>
              </Grid>

              <Grid size="grow">
                <Tooltip
                  title={<Trans>Upload</Trans>}
                  onClick={handleFileUploadClick}
                >
                  <Fab 
                    color='secondary' 
                    size='medium'
                    disabled={isSubmitting} 
                  >
                    <AttachFileIcon />
                  </Fab>
                </Tooltip>
              </Grid>
            </Grid>
          </form>
        </Box>
      </Box>
    </Paper>
  );
}