import { useFormContext } from 'react-hook-form';
import { useNavigate, useMatch } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import {
  IconChevronLeft,
  IconAspectRatioOff,
  IconAspectRatio,
  IconTrash,
} from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

import { logEvent } from 'src/config/logging';
import useUnsavedWarning from 'src/hooks/useUnsavedWarning';
import { EventName } from 'src/types/amplitude';
import { Article, LibraryValues } from 'src/types/libraries';
import { insertIf } from 'src/utils/arrays';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useCoverPicture from '../hooks/useCoverPicture';
import useUpdateLibrary from '../hooks/useUpdateLibrary';
import { librariesRoutes } from '../routes';

import CloseEditModal from './CloseEditModal';
import DeleteLibraryModal from './DeleteLibraryModal';
import StatusPill from './StatusPill';

export type HeaderProps = {
  library: Article;
  onOpenEdit?: () => void;
  onCloseEdit?: () => void;
};

export const Header = ({
  library,
  onOpenEdit = () => null,
  onCloseEdit = () => null,
}: HeaderProps) => {
  const { handleSubmit, formState } = useFormContext<LibraryValues>();
  const { t } = useLokaliseTranslation('general');
  const navigate = useNavigate();
  const theme = useTheme();

  const isEdit = !!useMatch(librariesRoutes.edit());

  const updateMutation = useUpdateLibrary(library, {
    onMutate: () => disableUnsavedWarning(),
    onSuccess: () => closeEdit(),
    onSettled: () => resetUnsavedWarning(),
  });

  const {
    modal: unsavedModal,
    disableUnsavedWarning,
    resetUnsavedWarning,
  } = useUnsavedWarning(CloseEditModal, !isEdit || !formState.isDirty);

  const { modal: deleteLibraryModal, showModal: showDeleteLibraryModal } =
    useModal(DeleteLibraryModal, undefined, {
      onCancel: () => resetUnsavedWarning(),
    });

  const {
    showCoverPicture,
    removeCoverPicture,
    addCoverPicture,
    removeCoverPictureModal,
  } = useCoverPicture();

  const handleDelete = () => {
    disableUnsavedWarning();
    showDeleteLibraryModal({ library });
  };

  const options = [
    {
      id: 'delete',
      title: t('delete'),
      onClick: handleDelete,
      Icon: IconTrash,
    },
    ...insertIf(showCoverPicture, {
      id: 'remove-cover-picture',
      title: t('cover_picture.delete.title'),
      onClick: removeCoverPicture,
      Icon: IconAspectRatioOff,
    }),
    ...insertIf(!showCoverPicture, {
      id: 'add-cover-picture',
      title: t('cover_picture.add.title'),
      onClick: addCoverPicture,
      Icon: IconAspectRatio,
    }),
  ];

  const openEdit = () => {
    onOpenEdit();
    logEvent(EventName.LIBRARY_CONTENT_EDIT_CLICK, {
      libraryId: library.id,
      parentId: library.parentId,
      title: library.title,
    });
    navigate(librariesRoutes.edit(library.id));
  };

  const closeEdit = () => {
    onCloseEdit();
    navigate(librariesRoutes.library(library.id));
  };

  const goBack = () =>
    library.parentId
      ? navigate(librariesRoutes.library(library.parentId))
      : navigate(librariesRoutes.base());

  const handleBack = () => (isEdit ? closeEdit() : goBack());

  const handleSave = handleSubmit(values => updateMutation.mutate(values));

  return (
    <>
      {removeCoverPictureModal}
      {deleteLibraryModal}
      {unsavedModal}
      <Stack
        sx={{
          width: '100%',
          backgroundColor: theme.palette.new.background.layout.tertiary,
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: 1,
          py: 1.5,
          px: 3,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'flex-start',
            alignItems: 'center',
            gap: 2,
          }}
        >
          <IconButton
            onClick={handleBack}
            aria-label={t('back')}
          >
            <IconChevronLeft />
          </IconButton>
          <Typography
            variant="globalL"
            fontWeight="fontWeightSemiBold"
          >
            {library.title}
          </Typography>
          {library.isEditor && isEdit && <StatusPill status={library.status} />}
        </Stack>
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'flex-end',
            alignItems: 'center',
            gap: 2,
          }}
        >
          {library.isEditor && !isEdit && (
            <Button
              variant="contained"
              color="primary"
              size="medium"
              onClick={openEdit}
            >
              {t('edit')}
            </Button>
          )}
          {library.isEditor && isEdit && (
            <>
              <Button
                variant="contained"
                color="primary"
                size="medium"
                onClick={handleSave}
                loading={updateMutation.isLoading || updateMutation.isSuccess}
              >
                {t('save_changes')}
              </Button>
              <HuMenuList options={options} />
            </>
          )}
        </Stack>
      </Stack>
    </>
  );
};

export default Header;
