import { FC, useState } from 'react';
import { useForm, FormProvider } from 'react-hook-form';

import { useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';

import '../i18n';

import Box from '@material-hu/mui/Box';
import Dialog from '@material-hu/mui/Dialog';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogTitle from '@material-hu/mui/DialogTitle';

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

import { logEvent } from 'src/config/logging';
import useGeneralError from 'src/hooks/useGeneralError';
import { useTranslation } from 'src/pages/dashboard/tickets/i18n';
import { createTicket } from 'src/services/tickets';
import { EventName } from 'src/types/amplitude';
import { Topic } from 'src/types/tickets';
import { getMessageErrorCode } from 'src/utils/tickets';

import { chatRoutes } from 'src/components/dashboard/chat/routes';
import FormTextField from 'src/components/FormInputs/FormTextField';
import { LoadingButton } from 'src/components/LoadingButton';

import FAQDialog from './FAQDialog';

type NewTicketDialogProps = Topic & {
  open: boolean;
  onClose?: () => void;
};

const NewTicketDialog: FC<NewTicketDialogProps> = props => {
  const {
    open,
    onClose,
    name,
    id,
    faq: { body },
  } = props;

  const [faqOpen, setFaqOpen] = useState<boolean>(false);

  const { t } = useTranslation();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();

  const { isLoading, mutate } = useMutation(createTicket, {
    onSuccess: response => {
      logEvent(EventName.TOPIC_TICKET_CREATE, {
        topicId: response.data.topic?.id,
        ticketId: response.data.id,
      });

      const chatId = response.data.chat.id;
      const state = response.data;

      onClose();
      reset();
      navigate(chatRoutes.thread.detail(chatId), { state });
    },
    onError: (err: any) =>
      showGeneralError(err, getMessageErrorCode(err.response?.data?.code, t)),
  });

  const form = useForm({
    defaultValues: {
      topic: name,
      subject: '',
      message: '',
    },
  });

  const { handleSubmit, reset } = form;

  const submit = values => {
    const formData = {
      topicId: id,
      subject: values.subject,
      firstMessage: values.message,
    };

    mutate(formData);
  };

  const openFaq = () => {
    setFaqOpen(true);
  };

  const closeFaq = () => {
    setFaqOpen(false);
  };

  return (
    <Box
      sx={{
        alignItems: 'center',
        backgroundColor: 'background.paper',
        display: 'flex',
        flexShrink: 0,
      }}
    >
      <FAQDialog
        open={faqOpen}
        onClose={closeFaq}
        body={body}
      />
      <Dialog
        open={open}
        onClose={onClose}
      >
        <DialogTitle>{t('NEW_TICKET')}</DialogTitle>
        <FormProvider {...form}>
          <form
            noValidate
            onSubmit={handleSubmit(submit)}
          >
            <DialogContent>
              <FormTextField
                name="topic"
                label={t('TOPIC')}
                placeholder={t('TOPIC')}
                fullWidth
                variant="standard"
                value={name}
                disabled={isLoading}
                InputProps={{
                  readOnly: true,
                }}
                sx={{
                  my: 1,
                }}
              />
              <FormTextField
                name="subject"
                label={t('SUBJECT')}
                placeholder={t('SUBJECT')}
                fullWidth
                variant="standard"
                disabled={isLoading}
                sx={{
                  my: 1,
                }}
              />
              <FormTextField
                name="message"
                label={t('MESSAGE')}
                placeholder={t('MESSAGE')}
                fullWidth
                variant="standard"
                disabled={isLoading}
                multiline
                sx={{
                  my: 1,
                }}
              />
            </DialogContent>
            <DialogActions>
              {body?.length > 0 && (
                <Button
                  color="primary"
                  variant="outlined"
                  type="button"
                  onClick={openFaq}
                >
                  {t('FAQ')}
                </Button>
              )}
              <LoadingButton
                color="primary"
                variant="contained"
                type="submit"
                disabled={isLoading}
                loading={isLoading}
                loadingPosition="start"
              >
                {isLoading ? t('LOADING_SEND') : t('SEND')}
              </LoadingButton>
            </DialogActions>
          </form>
        </FormProvider>
      </Dialog>
    </Box>
  );
};

export default NewTicketDialog;
