import { useEffect } from 'react';
import {
  DragDropContext,
  Draggable,
  type DropResult,
  // biome-ignore lint/style/noRestrictedImports: legacy usage, migration pending
} from 'react-beautiful-dnd';
import { Link as RouterLink, useNavigate, useParams } from 'react-router-dom';

import { type SearchControllerProps } from '@material-hu/hooks/useHuPagination';
import { useModal } from '@material-hu/hooks/useModal';
import CircleIcon from '@material-hu/icons/material/Circle';
import DragHandleIcon from '@material-hu/icons/material/DragHandle';
import IconButton from '@material-hu/mui/IconButton';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import usePermissions from 'src/hooks/usePermissions';
import ArrowLeftIcon from 'src/icons/ArrowLeft';
import PlusIcon from 'src/icons/Plus';
import { LibraryStatus } from 'src/types/library';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';
import { UserPermissions } from 'src/utils/permissions';

import CustomIcon from 'src/components/CustomIcon';
import StrictModeDroppable from 'src/components/StrictModeDroppable';

import { useGetLibraries } from '../../hooks/useGetLibraries';
import { useGetLibrary } from '../../hooks/useGetLibrary';
import useLibrariesTitle from '../../hooks/useLibrariesTitle';
import { useMoveArticleMutation } from '../../hooks/useMoveArticleMutation';
import LibraryPopup from '../../Library';
import { librariesRoutes } from '../../routes';
import { calculateNewLibraryPosition } from '../../utils';

import SidebarSkeleton from './SidebarSkeleton';

export type SidebarProps = {
  Search: (props: SearchControllerProps) => JSX.Element;
};

export const Sidebar = ({ Search }: SidebarProps) => {
  const { t } = useLokaliseTranslation('libraries');
  const { id } = useParams();
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();
  const libraryId = id ? parseInt(id) : undefined;
  const title = useLibrariesTitle();

  const { hasAll: canCreateLibraries } = usePermissions([
    UserPermissions.CREATE_KNOWLEDGE_LIBRARIES,
  ]);

  const librariesQuery = useGetLibraries();
  const libraryQuery = useGetLibrary(libraryId);

  const { data: { library, childrenArticles = [] } = {}, isLoading: loading } =
    libraryId ? libraryQuery : librariesQuery;

  const moveArticleMutation = useMoveArticleMutation();

  useEffect(() => {
    const input = document.querySelector(
      '#library-search-input-container input',
    );

    const handleSearchFocus = () => {
      logEvent(LogEvents.WIDGET_LIBRARY_SEARCH);
    };

    input?.addEventListener('focus', handleSearchFocus);

    return () => {
      input?.removeEventListener('focus', handleSearchFocus);
    };
  }, []);

  const { showModal: showNewArticleModal, modal: newArticleModal } = useModal(
    LibraryPopup,
    { maxWidth: 'md', fullWidth: true },
    { parent: library },
  );

  const handleDragEnd = ({ source, destination, draggableId }: DropResult) => {
    if (!destination) return;

    const isSamePosition =
      source.index === destination.index &&
      source.droppableId === destination.droppableId;

    if (isSamePosition) return;

    const fromIndex = source.index;
    const toIndex = destination.index;

    const newPosition = calculateNewLibraryPosition(
      childrenArticles,
      fromIndex,
      toIndex,
    );

    if (newPosition === undefined) return;

    moveArticleMutation.mutate({
      articleId: parseInt(draggableId),
      destinationPosition: newPosition,
      libraryId,
    });
  };

  return (
    <>
      {newArticleModal}
      <Stack
        sx={{
          backgroundColor: 'background.paper',
          borderRight: 1,
          borderColor: 'divider',
          width: 280,
          minWidth: 280,
        }}
      >
        <HuGoThemeProvider>
          <Stack
            id="library-search-input-container"
            sx={{ p: 1, pt: 1.5 }}
          >
            <Search
              inputProps={{
                placeholder: t('general:search'),
                variant: 'custom',
              }}
            />
          </Stack>
        </HuGoThemeProvider>
        {loading && <SidebarSkeleton />}
        {!loading && (
          <>
            {library && (
              <>
                <Button
                  variant="outlined"
                  onClick={() =>
                    library?.parentId
                      ? navigate(librariesRoutes.library(library?.parentId))
                      : navigate(librariesRoutes.base())
                  }
                  sx={{ m: 3, mb: 0, width: '2px', textAlign: 'center', px: 0 }}
                >
                  <ArrowLeftIcon fontSize="small" />
                </Button>
                <Stack
                  alignItems="center"
                  direction="row"
                  sx={{ px: 3, py: 1 }}
                >
                  <CustomIcon
                    icon={library.icon}
                    size={40}
                  />
                  <Stack
                    sx={{
                      maxHeight: '150px',
                      maxWidth: '160px',
                      py: 3,
                      pl: 2,
                      pr: 1,
                    }}
                  >
                    <HuGoThemeProvider>
                      <Typography
                        variant="globalM"
                        fontWeight="fontWeightSemiBold"
                        sx={{
                          py: 3,
                          px: 1.5,
                          display: '-webkit-box',
                          overflow: 'hidden',
                          WebkitBoxOrient: 'vertical',
                          WebkitLineClamp: 3,
                          wordWrap: 'break-word',
                        }}
                      >
                        {library.title}
                      </Typography>
                    </HuGoThemeProvider>
                  </Stack>
                  <CircleIcon
                    sx={{ fontSize: '12px', ml: 'auto' }}
                    color={
                      library.status === LibraryStatus.ENABLED
                        ? 'success'
                        : 'disabled'
                    }
                  />
                </Stack>
                <Typography
                  variant="body1"
                  sx={{ display: 'inline', p: 3, fontWeight: 'bold' }}
                  color="textPrimary"
                >
                  {t('subarticle.title_other')}
                </Typography>
                {!childrenArticles?.length && (
                  <Typography
                    variant="subtitle2"
                    color="textSecondary"
                    sx={{ ml: 3, mb: 3 }}
                  >
                    {t('subarticle.empty')}
                  </Typography>
                )}
              </>
            )}
            {!library && (
              <HuGoThemeProvider>
                <Typography
                  variant="globalM"
                  fontWeight="fontWeightSemiBold"
                  sx={{
                    display: 'inline',
                    py: 3,
                    px: 1.5,
                  }}
                >
                  {title}
                </Typography>
              </HuGoThemeProvider>
            )}
            <DragDropContext onDragEnd={handleDragEnd}>
              <StrictModeDroppable droppableId="LIBRARY_DROPPABLE_ID">
                {provided => (
                  <Stack
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                    sx={{ flex: '1 1 auto', overflow: 'auto' }}
                  >
                    {childrenArticles?.map((children, index) => (
                      <Draggable
                        draggableId={children.id.toString()}
                        index={index}
                        key={children.id}
                      >
                        {(draggableStepProvided): JSX.Element => (
                          <Stack
                            key={children.id}
                            alignItems="center"
                            direction="row"
                            sx={{ px: 3, py: 1 }}
                            ref={draggableStepProvided.innerRef}
                            {...draggableStepProvided.draggableProps}
                          >
                            <IconButton
                              {...draggableStepProvided.dragHandleProps}
                              disabled={false}
                              edge="start"
                            >
                              <DragHandleIcon
                                sx={{ fontSize: '18px', mr: '10px' }}
                              />
                            </IconButton>
                            <Link
                              component={RouterLink}
                              to={librariesRoutes.library(children?.id)}
                              color="inherit"
                              sx={{
                                flex: 1,
                                maxWidth: '190px',
                                height: library && 45,
                              }}
                            >
                              <Stack
                                direction="row"
                                spacing={3}
                                alignItems="center"
                                height={library ? 45 : undefined}
                              >
                                <CustomIcon
                                  icon={children.icon}
                                  size={30}
                                />
                                <Typography
                                  color="textSecondary"
                                  sx={{
                                    width: '100%',
                                    display: '-webkit-box',
                                    overflow: 'hidden',
                                    WebkitBoxOrient: 'vertical',
                                    WebkitLineClamp: library ? 2 : 3,
                                    wordWrap: 'break-word',
                                  }}
                                >
                                  {children.title}
                                </Typography>
                                <CircleIcon
                                  sx={{ fontSize: '12px', ml: 'auto' }}
                                  color={
                                    children.status === LibraryStatus.ENABLED
                                      ? 'success'
                                      : 'disabled'
                                  }
                                />
                              </Stack>
                            </Link>
                          </Stack>
                        )}
                      </Draggable>
                    ))}
                    {provided.placeholder}
                  </Stack>
                )}
              </StrictModeDroppable>
            </DragDropContext>
            {canCreateLibraries && (
              <Stack sx={{ p: 3 }}>
                <Button
                  onClick={() => showNewArticleModal()}
                  startIcon={<PlusIcon fontSize="small" />}
                  variant="outlined"
                >
                  {t(
                    `${library ? 'subarticle.create.title' : 'article.create'}`,
                  )}
                </Button>
              </Stack>
            )}
          </>
        )}
      </Stack>
    </>
  );
};
