import { type FC } from 'react';
import { useParams } from 'react-router';

import {
  IconArrowLeft,
  IconDownload,
  IconX,
  IconZoomIn,
  IconZoomOut,
} from '@material-hu/icons/tabler';
import DialogTitle from '@material-hu/mui/DialogTitle';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { useAuth } from 'src/contexts/JWTContext';
import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import {
  type HuDataMessage,
  type SendFileItem,
} from 'src/pages/dashboard/Conversations/types';
import {
  getMediaUrl,
  isVideoAttachment,
} from 'src/pages/dashboard/Conversations/utils';
import { formatMessageDate, formatMessageShortDate } from 'src/utils/date';
import { download, downloadUrl } from 'src/utils/files';
import { getInitials } from 'src/utils/userUtils';

import {
  useGetConversationInfo,
  useGetCorrectAttachmentUrl,
} from '../../../hooks/useConversationsQueries';
import LazySecureImage from '../LazySecureImage';

type MediaVisualizerHeaderProps = {
  onClose: () => void;
  onBack?: () => void;
  onZoomIn?: () => void;
  onZoomOut?: () => void;
  zoom?: number;
  selectedAttachment: SendFileItem;
  huData?: HuDataMessage;
  username: string;
};

const MediaVisualizerHeader: FC<MediaVisualizerHeaderProps> = ({
  onClose,
  onBack,
  onZoomIn,
  onZoomOut,
  zoom = 1,
  selectedAttachment,
  huData,
  username,
}) => {
  const { id } = useParams<{ id: string }>();
  const { user: loggedUser } = useAuth();
  const { conversation } = useGetConversationInfo({ id });
  const groupName = conversation?.name;
  const mediaUrl = getMediaUrl(selectedAttachment);
  const { data: secureUrl } = useGetCorrectAttachmentUrl({
    url: mediaUrl,
    enabledToShowError: false,
    enabled: !!mediaUrl,
  });
  const isVideo = isVideoAttachment(selectedAttachment);

  const handleDownload = () => {
    const urlToDownload = secureUrl ?? mediaUrl;
    const filename = selectedAttachment.filename;
    if (!urlToDownload) return;
    if (urlToDownload.startsWith('blob:')) {
      download(urlToDownload, filename);
    } else {
      downloadUrl(urlToDownload, filename);
    }
  };
  return (
    <DialogTitle
      sx={{
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        px: 2,
        py: 1.5,
        borderBottom: theme =>
          `1px solid ${theme.palette.new.border.neutral.default}`,
      }}
    >
      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
        <IconButton onClick={onBack}>
          <IconArrowLeft />
        </IconButton>

        {huData && (
          <>
            <LazySecureImage
              url={huData.picture_asset_url}
              isAvatar
              imageClass={BUNNY_IMAGE_CLASSES.AVATAR}
              avatarProps={{
                text: getInitials(username),
              }}
            />
            <Stack>
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
              >
                {username}
              </Typography>
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}
              >
                <Typography
                  variant="globalXS"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                  }}
                >
                  {loggedUser &&
                    `${formatMessageShortDate(huData.message_ts, loggedUser)}, ${formatMessageDate(huData.message_ts, loggedUser)}`}
                </Typography>
                {groupName && (
                  <>
                    <Typography
                      variant="globalM"
                      fontWeight="fontWeightSemiBold"
                      sx={{
                        color: theme => theme.palette.new.text.neutral.lighter,
                        lineHeight: 1,
                      }}
                    >
                      •
                    </Typography>
                    <Typography
                      variant="globalXS"
                      sx={{
                        color: theme => theme.palette.new.text.neutral.lighter,
                      }}
                    >
                      {groupName}
                    </Typography>
                  </>
                )}
              </Stack>
            </Stack>
          </>
        )}
      </Stack>

      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}>
        {!isVideo && (
          <>
            <IconButton onClick={onZoomIn}>
              <IconZoomIn />
            </IconButton>
            <IconButton
              onClick={onZoomOut}
              disabled={zoom <= 1}
            >
              <IconZoomOut />
            </IconButton>
          </>
        )}
        {huData && (
          <IconButton onClick={handleDownload}>
            <IconDownload />
          </IconButton>
        )}
        <IconButton onClick={onClose}>
          <IconX />
        </IconButton>
      </Stack>
    </DialogTitle>
  );
};

export default MediaVisualizerHeader;
