import { type FC, useEffect, useRef, useState } from 'react';

import { IconChevronLeft, IconChevronRight } from '@material-hu/icons/tabler';
import DialogContent from '@material-hu/mui/DialogContent';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';

import { HIDE_TIMEOUT_MS } from 'src/pages/dashboard/Conversations/constants';
import {
  type AttachmentLoadError,
  type HuDataMessage,
  type SendFileItem,
  type SendFilesList,
} from 'src/pages/dashboard/Conversations/types';

import FloatingMessage from './FloatingMessage';
import Footer from './Footer';
import MediaError from './MediaError';
import MediaRender from './MediaRender';

type MediaVisualizerBodyProps = {
  conversationId?: string;
  attachments: SendFilesList;
  selectedAttachment: SendFileItem;
  selectedIndex: number;
  onSelectIndex: (index: number) => void;
  onPrev: () => void;
  onNext: () => void;
  isSecure: boolean;
  huData?: HuDataMessage;
  text?: string;
  zoom: number;
  onZoom?: (newZoom: number) => void;
  onClose: () => void;
  onReply?: () => void;
};

const MediaVisualizerBody: FC<MediaVisualizerBodyProps> = ({
  conversationId,
  attachments,
  selectedAttachment,
  selectedIndex,
  onSelectIndex,
  onPrev,
  onNext,
  isSecure,
  huData,
  text,
  zoom,
  onZoom,
  onClose,
  onReply,
}) => {
  const isManyAttachments = attachments.length > 1;
  const [attachmentLoadError, setAttachmentLoadError] =
    useState<AttachmentLoadError>([]);
  const [isFloatingVisible, setIsFloatingVisible] = useState(false);
  const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    setAttachmentLoadError([]);
  }, [selectedIndex]);

  useEffect(
    () => () => {
      if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    },
    [],
  );

  const startHideTimer = () => {
    if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    hideTimerRef.current = setTimeout(
      () => setIsFloatingVisible(false),
      HIDE_TIMEOUT_MS,
    );
  };

  const showFloatingMessage = () => {
    setIsFloatingVisible(true);
    startHideTimer();
  };

  const keepFloatingMessageAlive = () => {
    if (!isFloatingVisible) return;
    startHideTimer();
  };

  const hideFloatingMessage = () => {
    if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    setIsFloatingVisible(false);
  };

  const handleRetry = () => {
    const pending = attachmentLoadError;
    setAttachmentLoadError([]);
    pending.forEach(error => error.retry?.());
  };

  const isZoomed = zoom > 1;
  const chevronSx = {
    flexShrink: 0,
    display: isManyAttachments && !isZoomed ? 'inline-flex' : 'none',
  } as const;

  return (
    <DialogContent
      onMouseMove={keepFloatingMessageAlive}
      onMouseLeave={hideFloatingMessage}
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'stretch',
        overflow: 'hidden',
        px: 0,
        py: 0,
      }}
    >
      <Stack
        sx={{
          flex: 1,
          minHeight: 0,
          gap: 3,
          overflow: 'hidden',
          flexDirection: 'row',
          alignItems: 'center',
          px: isZoomed ? 0 : 3,
          pt: isZoomed ? 0 : 4,
          pb: 0,
          transition: 'padding 0.2s ease',
        }}
      >
        <IconButton
          sx={chevronSx}
          onClick={onPrev}
        >
          <IconChevronLeft />
        </IconButton>

        <Stack
          onMouseEnter={showFloatingMessage}
          onMouseMove={showFloatingMessage}
          sx={{
            flex: 1,
            minWidth: 0,
            height: '100%',
            alignItems: 'center',
            justifyContent: 'center',
            overflow: 'hidden',
          }}
        >
          {attachmentLoadError.length > 0 && (
            <MediaError
              onRetry={handleRetry}
              amountOfErrors={attachmentLoadError.length}
              onClose={onClose}
            />
          )}

          {attachmentLoadError.length === 0 && (
            <MediaRender
              key={selectedAttachment.id}
              conversationId={conversationId}
              attachment={selectedAttachment}
              onUpdateAttachmentLoadError={setAttachmentLoadError}
              zoom={zoom}
              onZoom={onZoom}
              isSecure={isSecure}
              controlsVisible={isFloatingVisible}
            />
          )}
        </Stack>

        <IconButton
          sx={chevronSx}
          onClick={onNext}
        >
          <IconChevronRight />
        </IconButton>
      </Stack>

      <Stack
        sx={{
          position: 'relative',
          width: '100%',
          px: 3,
          py: 2,
        }}
      >
        <FloatingMessage
          key={selectedAttachment.id}
          text={text}
          highlightedSpans={huData?.highlighted_spans ?? []}
          visible={isFloatingVisible}
        />
        <Footer
          attachments={attachments}
          selectedIndex={selectedIndex}
          onSelectIndex={onSelectIndex}
          isSecure={isSecure}
          onReply={onReply}
        />
      </Stack>
    </DialogContent>
  );
};

export default MediaVisualizerBody;
