import { type FC } from 'react';
import { Controller, FormProvider } from 'react-hook-form';

import ArrowDownward from '@material-hu/icons/material/ArrowDownward';
import {
  IconFile,
  IconMoodHappy,
  IconPhoto,
  IconPlus,
  IconSend,
} from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import ClickAwayListener from '@material-hu/mui/ClickAwayListener';
import Collapse from '@material-hu/mui/Collapse';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import TextField from '@material-hu/mui/TextField';
import { type FileAsset } from '@material-hu/types/attachments';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuMenu from '@material-hu/components/design-system/Menu';

import useNewTheme from 'src/hooks/useNewTheme';
import { StyledContainer } from 'src/pages/dashboard/Conversations/components/ConversationsThread/ConversationsThreadFooter/InputEditor/InputRenderer';
import { type Task } from 'src/pages/dashboard/serviceManagement/types';
import { safeConvertFileAssetToAttachment } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import PdfViewer from 'src/components/attachment/PdfViewer';
import Picker from 'src/components/dashboard/reactions/Picker';

import { fileAccept, imageAccept } from '../../../../constants';

import CommentAttachmentsList from './CommentAttachmentsList';
import FileInputMenuItem from './FileInputMenuItem';
import { useCommentForm } from './useCommentForm';

type CommentFormProps = {
  task: Task;
  isAgentWorkspace: boolean;
  onScrollToBottom: () => void;
  showUnreadCommentsBubble: boolean;
  unreadCommentsCount: number;
};

const CommentForm: FC<CommentFormProps> = ({
  task,
  isAgentWorkspace,
  onScrollToBottom,
  showUnreadCommentsBubble,
  unreadCommentsCount,
}) => {
  const { t } = useLokaliseTranslation(['service_management', 'general']);
  const NewThemeProvider = useNewTheme();

  const {
    form,
    inputRef,
    anchorEl,
    open,
    pickerOpen,
    setPickerOpen,
    pdfFileToPreview,
    setPdfFileToPreview,
    setAttachmentTypeToAdd,
    images,
    files,
    watchedMessage,
    mutation,
    emojiCategories,
    showCommentAttachments,
    isSendDisabled,
    handleOpenAttachmentMenu,
    handleCloseAttachmentMenu,
    handleAddImages,
    handleAddFiles,
    handleRemoveAttachment,
    handleOpenFilePreview,
    handleSelectEmoji,
    handlePaste,
    handleSubmit,
    submit,
  } = useCommentForm({ task, isAgentWorkspace, onScrollToBottom });

  return (
    <>
      <Stack
        sx={{
          position: 'relative',
          backgroundColor: theme =>
            theme.palette.new.background.layout.tertiary,
          p: 2,
          width: '100%',
          borderTop: theme =>
            `1px solid ${theme.palette.new.border.neutral.divider}`,
        }}
      >
        <FormProvider {...form}>
          <form
            noValidate
            onSubmit={handleSubmit(submit)}
          >
            <Stack
              sx={{ flexDirection: 'row', width: '100%', alignItems: 'center' }}
            >
              <HuMenu
                id="message-actions-menu"
                anchorEl={anchorEl}
                open={open}
                onClose={handleCloseAttachmentMenu}
                position="left"
                fixedDimensions={false}
                sx={{ marginTop: showCommentAttachments ? '-150px' : '-50px' }}
              >
                <FileInputMenuItem
                  title={t('FILES')}
                  icon={<IconFile size={20} />}
                  inputProps={{ accept: fileAccept, multiple: true }}
                  onChange={handleAddFiles}
                  onClick={() => setAttachmentTypeToAdd('files')}
                />
                <FileInputMenuItem
                  title={t('IMAGES')}
                  icon={<IconPhoto size={20} />}
                  inputProps={{ multiple: true, accept: imageAccept }}
                  onClick={() => setAttachmentTypeToAdd('images')}
                  onChange={handleAddImages}
                />
              </HuMenu>
              <Button
                variant="tertiary"
                sx={{ mr: 1, p: 0, minWidth: 40 }}
                onClick={handleOpenAttachmentMenu}
              >
                <IconPlus />
              </Button>
              <ClickAwayListener
                onClickAway={() => {
                  if (pickerOpen) setPickerOpen(false);
                }}
              >
                <StyledContainer
                  isEmpty={!watchedMessage}
                  isFocused={false}
                  sx={{ flex: 1, position: 'relative', alignItems: 'center' }}
                >
                  <Box sx={{ position: 'relative' }}>
                    <Collapse
                      id="emoji-picker-menu"
                      in={pickerOpen}
                      orientation="vertical"
                      aria-labelledby="emoji-picker-button"
                      sx={{
                        position: 'absolute',
                        bottom: '100%',
                        left: 0,
                        marginBottom: '20px',
                        width: 420,
                        maxWidth: '90vw',
                        boxShadow: theme => theme.shadows[2],
                        borderRadius: 1,
                        zIndex: 50000,
                        backgroundColor: 'white',
                      }}
                    >
                      <Picker
                        onEmojiClick={handleSelectEmoji}
                        searchPlaceholder={t('general:search')}
                        categories={emojiCategories}
                      />
                    </Collapse>
                    <IconButton
                      id="emoji-picker-button"
                      aria-controls="emoji-picker-menu"
                      aria-label={t('pick_emoji')}
                      aria-expanded={pickerOpen ? 'true' : undefined}
                      onClick={() => setPickerOpen(prev => !prev)}
                      sx={{
                        color: theme =>
                          pickerOpen
                            ? theme.palette.ilustrations?.primaryIlus
                            : theme.palette.text.secondary,
                        ':hover': { backgroundColor: 'transparent' },
                      }}
                    >
                      <IconMoodHappy size={24} />
                    </IconButton>
                  </Box>
                  <Controller
                    name="message"
                    control={form.control}
                    render={({ field }) => (
                      <TextField
                        inputRef={inputRef}
                        {...field}
                        fullWidth
                        multiline
                        minRows={1}
                        maxRows={4}
                        onPaste={handlePaste}
                        variant="standard"
                        placeholder={t('write_comment')}
                        disabled={mutation.isLoading}
                        onKeyDown={e => {
                          if (e.key === 'Enter' && !e.shiftKey) {
                            e.preventDefault();
                            handleSubmit(submit)();
                          }
                        }}
                        InputProps={{ disableUnderline: true }}
                        sx={{
                          flex: 1,
                          '& .MuiInputBase-root': {
                            padding: '10px 8px 10px 0',
                          },
                          '& textarea': {
                            overflow: 'auto !important',
                            maxHeight: '100px',
                          },
                          '& .MuiInputBase-input::placeholder': {
                            fontSize: '14px',
                            opacity: 0.6,
                          },
                        }}
                        inputProps={{ spellCheck: 'true', autoCorrect: 'on' }}
                      />
                    )}
                  />
                </StyledContainer>
              </ClickAwayListener>
              <IconButton
                type="submit"
                variant="secondary"
                sx={{ ml: 1, height: '40px', width: '40px' }}
                disabled={isSendDisabled}
              >
                <IconSend />
              </IconButton>
            </Stack>
          </form>
        </FormProvider>
        {showUnreadCommentsBubble && (
          <Button
            variant="primary"
            sx={{
              width: 'fit-content',
              position: 'absolute',
              bottom: '90px',
              left: '50%',
              transform: 'translateX(-50%)',
              zIndex: 1,
            }}
            endIcon={<ArrowDownward />}
            onClick={onScrollToBottom}
          >
            {t('comments_new_messages', { count: unreadCommentsCount })}
          </Button>
        )}
      </Stack>
      {showCommentAttachments && (
        <CommentAttachmentsList
          images={images}
          files={files}
          onDelete={handleRemoveAttachment}
          onOpenFile={handleOpenFilePreview}
        />
      )}
      <NewThemeProvider>
        {pdfFileToPreview && (
          <PdfViewer
            file={safeConvertFileAssetToAttachment(
              pdfFileToPreview as FileAsset,
            )}
            onClose={() => setPdfFileToPreview(null)}
          />
        )}
      </NewThemeProvider>
    </>
  );
};

export default CommentForm;
