import { useState, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider } from 'react-hook-form';
import { useMatch, Outlet } from 'react-router-dom';

import { useHuPagination } from '@material-hu/hooks/useHuPagination';
import { useModal } from '@material-hu/hooks/useModal';
import Stack from '@material-hu/mui/Stack';

import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { librariesRoutes } from '../routes';

import CloseEditModal from './CloseEditModal';
import LibrarySearchResult from './LibrarySearchResult';
import LibrarySidebar from './LibrarySidebar';

export type LibraryLayoutProps = {
  title?: string;
};

export const LibraryLayout = ({ title }: LibraryLayoutProps) => {
  const [showSearch, setShowSearch] = useState(false);

  const { t } = useLokaliseTranslation('apps');

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

  const {
    modal: unsavedModal,
    showModal: showUnsavedModal,
    closeModal: closeUnsavedModal,
  } = useModal(CloseEditModal, undefined, {
    onConfirm: () => {
      closeUnsavedModal();
      setShowSearch(true);
    },
    onClose: () => {
      closeUnsavedModal();
      setParams(null);
    },
  });

  const { form, params, setParams, hasSearch, Search, Pagination } =
    useHuPagination();

  useEffect(() => {
    if (!hasSearch) return setShowSearch(false);
    if (isEdit) return showUnsavedModal();
    return setShowSearch(true);
  }, [isEdit, hasSearch]);

  useEffect(() => {
    if (isEdit) setShowSearch(false);
  }, [isEdit]);

  const handleSearchBack = () => setParams(null);

  return (
    <>
      {unsavedModal}
      <Helmet>
        <title>
          {formatTitle(title || t('title_view_knowledge_libraries'))}
        </title>
      </Helmet>
      <FormProvider {...form}>
        <Stack
          sx={{
            flexDirection: 'row',
            height: '100%',
            overflow: 'hidden',
          }}
        >
          <LibrarySidebar Search={Search} />
          {!showSearch && <Outlet />}
          {showSearch && (
            <LibrarySearchResult
              Pagination={Pagination}
              params={params}
              onBack={handleSearchBack}
            />
          )}
        </Stack>
      </FormProvider>
    </>
  );
};

export default LibraryLayout;
