import { useEffect, useState } from 'react';
import {
  DragDropContext,
  Draggable,
  type DraggableProvided,
  type DroppableProvided,
  // biome-ignore lint/style/noRestrictedImports: legacy usage, migration pending
} from 'react-beautiful-dnd';

import CloseIcon from '@material-hu/icons/material/Close';
import { IconPlayerPlay } from '@material-hu/icons/tabler';
import CardMedia from '@material-hu/mui/CardMedia';
import IconButton from '@material-hu/mui/IconButton';
import ImageListItem from '@material-hu/mui/ImageListItem';
import Stack, { type StackProps } from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';

import HuTooltip from '@material-hu/components/design-system/Tooltip';

import useDragEnd, { type DragProps } from 'src/hooks/useDragEnd';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { type Attachment, FileTypes } from 'src/types/attachments';
import { type File } from 'src/types/files';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { sortByPosition } from 'src/utils/position';

import StrictModeDroppable from '../StrictModeDroppable';

import FilePreview from './FilePreview';

type AttachmentsMediaListProps = StackProps & {
  images?: Attachment[];
  videos?: Attachment[];
  onDelete?: (media: Attachment, index: number) => void;
  disabled?: boolean;
  isPost?: boolean;
  isComment?: boolean;
  handleChangePositionMultimedia?: Function;
};

const DROPPABLE_ID = 'ATTACHMENTS_MEDIA';

const AttachmentsMediaList = ({
  images = [],
  videos = [],
  onDelete,
  disabled = false,
  isPost = false,
  isComment = false,
  handleChangePositionMultimedia,
  ...stackProps
}: AttachmentsMediaListProps) => {
  const { palette } = useTheme();
  const [reorderedAttachments, setReorderedAttachments] = useState<
    Attachment[] | null
  >(null);
  const [previewMediaIndex, setPreviewMediaIndex] = useState<number | null>(
    null,
  );
  const [dialogOpen, setDialogOpen] = useState(false);
  const HugoThemeProvider = useHuGoTheme();
  const { t } = useTranslation();

  const handleShowMediaPreview = (index: number) => {
    if (disabled) return;
    setPreviewMediaIndex(index);
    setDialogOpen(true);
  };

  const handleCloseMediaPreview = () => {
    setDialogOpen(false);
  };

  const handleGoBack = () => {
    if (reorderedAttachments === null || previewMediaIndex === null) return;

    setPreviewMediaIndex(
      previewMediaIndex === 0
        ? reorderedAttachments.length - 1
        : previewMediaIndex - 1,
    );
  };

  const handleGoForward = () => {
    if (reorderedAttachments === null || previewMediaIndex === null) return;

    setPreviewMediaIndex(
      previewMediaIndex === reorderedAttachments.length - 1
        ? 0
        : previewMediaIndex + 1,
    );
  };

  useEffect(() => {
    setReorderedAttachments(sortByPosition([...images, ...videos]));
  }, [images, videos]);

  const renderItem = (item: Attachment, index: number) => {
    const isVideoAttachment = item.type === FileTypes.VIDEO;
    return (
      <Draggable
        draggableId={item.url?.toString() ?? ''}
        index={index}
        key={item.url?.toString() ?? ''}
        disableInteractiveElementBlocking={isVideoAttachment}
        isDragDisabled={disabled}
      >
        {(draggableProvided: DraggableProvided) => (
          <ImageListItem
            ref={draggableProvided.innerRef}
            {...draggableProvided.draggableProps}
            {...draggableProvided.dragHandleProps}
            sx={{
              width: 'fit-content',
              height: 'fit-content',
              pt: 1.5,
              pr: 1.5,
              position: 'relative',
            }}
          >
            <Stack
              sx={{
                position: 'relative',
                borderRadius: isPost || isComment ? '10px' : '',
                ...(!disabled && {
                  '&:hover': {
                    cursor: 'pointer',
                    '& .media-hover-overlay': {
                      opacity: 0.6,
                    },
                    '& .media-hover-icon': {
                      opacity: 1,
                    },
                  },
                }),
              }}
              onClick={() => handleShowMediaPreview(index)}
            >
              <CardMedia
                sx={{
                  height: () => {
                    if (isPost) return 70;
                    if (isComment) return 'auto';
                    return 250;
                  },
                  width: isPost || isComment ? 70 : 'auto',
                  borderRadius: isPost || isComment ? '10px' : '',
                  objectFit: isPost ? 'cover' : 'contain',
                  objectPosition: 'center',
                  cursor: disabled ? 'default' : 'pointer',
                  ...(isVideoAttachment && { background: 'common.black' }),
                }}
                component={isVideoAttachment ? 'video' : 'img'}
                src={item.url}
                alt={item.name}
                {...(isVideoAttachment && {
                  controls: false,
                  muted: true,
                  preload: 'metadata',
                })}
              />
              <Stack
                className="media-hover-overlay"
                sx={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  backgroundColor: 'common.black',
                  opacity: 0,
                  transition: 'opacity 0.3s ease',
                  borderRadius: 'inherit',
                }}
              />
              {isVideoAttachment && (
                <Stack
                  className="media-hover-icon"
                  sx={{
                    position: 'absolute',
                    top: '50%',
                    left: '50%',
                    transform: 'translate(-50%, -50%)',
                    color: 'common.white',
                    opacity: 0,
                    transition: 'opacity 0.3s ease',
                    pointerEvents: 'none',
                  }}
                >
                  <IconPlayerPlay />
                </Stack>
              )}
            </Stack>
            {onDelete && (
              <HuTooltip title={t('ELIMINATE')}>
                <span>
                  <IconButton
                    size="small"
                    sx={{
                      p: 0.5,
                      position: 'absolute',
                      borderRadius: '10px',
                      right: 0,
                      top: 0,
                      backgroundColor: alpha(
                        palette.new.background.elements.inverted,
                        0.6,
                      ),
                      '&:hover': {
                        backgroundColor:
                          palette.new.background.elements.inverted,
                      },
                      '& svg': {
                        color: palette.new.text.neutral.inverted,
                        fontSize: '16px',
                      },
                    }}
                    disabled={disabled}
                    onClick={event => {
                      event.stopPropagation();
                      onDelete(item, index);
                    }}
                  >
                    <CloseIcon />
                  </IconButton>
                </span>
              </HuTooltip>
            )}
          </ImageListItem>
        )}
      </Draggable>
    );
  };

  const dragAttachmentMedia = ({ destination, source }: DragProps) => {
    if (disabled) return;
    if (reorderedAttachments === null) return;

    const draggableAttachments = [...reorderedAttachments];
    const movedAttachment = reorderedAttachments[source.index];
    draggableAttachments.splice(source.index, 1);
    draggableAttachments.splice(destination?.index ?? 0, 0, movedAttachment);
    setReorderedAttachments(draggableAttachments);
    handleChangePositionMultimedia?.(draggableAttachments);
  };

  const { handleDragEnd } = useDragEnd(dragAttachmentMedia);

  return (
    <HugoThemeProvider>
      <Stack
        {...stackProps}
        sx={{ width: '100%', ...stackProps.sx }}
      >
        <DragDropContext onDragEnd={handleDragEnd}>
          <StrictModeDroppable
            droppableId={DROPPABLE_ID}
            direction="horizontal"
          >
            {(provided: DroppableProvided) => (
              <Stack
                ref={provided.innerRef}
                {...provided.droppableProps}
                sx={{
                  overflowX: 'auto',
                  maxHeight: !isPost ? 510 : 'auto',
                  flexDirection: 'row',
                  gap: 0.5,
                  pt: 1,
                  pb: 1,
                }}
              >
                {reorderedAttachments?.map(renderItem)}
                {provided.placeholder}
              </Stack>
            )}
          </StrictModeDroppable>
        </DragDropContext>
        {previewMediaIndex !== null && reorderedAttachments !== null && (
          <FilePreview
            isPost
            open={dialogOpen}
            currentFile={
              reorderedAttachments[previewMediaIndex] as Partial<File> &
                Partial<Attachment>
            }
            isLoadingMedia={!reorderedAttachments[previewMediaIndex]}
            onGoBack={handleGoBack}
            onGoForward={handleGoForward}
            headerProps={{
              onClose: handleCloseMediaPreview,
            }}
          />
        )}
      </Stack>
    </HugoThemeProvider>
  );
};

export default AttachmentsMediaList;
