import { type FC } from 'react';
import { useTranslation } from 'react-i18next';

import DownloadIcon from '@material-hu/icons/material/Download';
import PauseIcon from '@material-hu/icons/material/Pause';
import PlayIcon from '@material-hu/icons/material/PlayArrowRounded';
import { IconFile } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';
import Slider from '@material-hu/mui/Slider';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';

import { useAudioPlayback } from 'src/hooks/useAudioPlayback';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  formatAudioSliderValue,
  formatAudioTime,
  getAudioButtonLabel,
} from 'src/utils/attachments';

import EllipsisTooltip from 'src/components/EllipsisTooltip';

type PostAudioProps = {
  src: string;
  name?: string;
  duration?: number;
  messageId?: string | number;
};

const PostAudio: FC<PostAudioProps> = props => {
  const { src, name, duration, messageId } = props;

  const { t } = useTranslation('attachments');
  const HugoThemeProvider = useHuGoTheme();

  const {
    audioRef,
    currentTime,
    isPlaying,
    isLoading,
    durationSeconds,
    togglePlay,
    handleEnded,
    handleTimeUpdate,
    handleSlideChange,
    handleKeyDown,
    handleLoadStart,
    handleCanPlayThrough,
    handleLoadedMetadata,
    getCurrentTime,
  } = useAudioPlayback({ src, duration, messageId });

  const displayTime = formatAudioTime(getCurrentTime());
  const totalTime = formatAudioTime(durationSeconds);

  return (
    <HugoThemeProvider>
      <Box
        aria-label={t('audio_player') as string}
        onKeyDown={handleKeyDown}
        sx={{
          border: 1,
          borderColor: 'divider',
          borderRadius: 2,
          p: 2,
          display: 'flex',
          alignItems: 'center',
          gap: 1.5,
          width: '100%',
          maxWidth: '400px',
        }}
      >
        <audio
          src={src}
          controls={false}
          ref={audioRef}
          onEnded={handleEnded}
          onTimeUpdate={handleTimeUpdate}
          onLoadStart={handleLoadStart}
          onCanPlayThrough={handleCanPlayThrough}
          onLoadedMetadata={handleLoadedMetadata}
        />

        <HuAvatar
          Icon={IconFile}
          color="primary"
        />

        <Box sx={{ flex: 1, minWidth: 0 }}>
          {name && (
            <EllipsisTooltip title={name}>
              <Typography
                variant="globalS"
                fontWeight="fontWeightSemiBold"
                sx={{
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  display: 'block',
                }}
              >
                {name}
              </Typography>
            </EllipsisTooltip>
          )}

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Slider
              aria-label={t('audio_slider')}
              aria-valuetext={formatAudioSliderValue(
                currentTime,
                durationSeconds,
              )}
              name="post-audio-slider"
              step={0.2}
              min={0}
              max={durationSeconds}
              value={currentTime}
              onChange={handleSlideChange}
              size="small"
              sx={{ flex: 1 }}
            />
            <Typography
              variant="globalXS"
              color={theme => theme.palette.new.text.neutral.lighter}
              sx={{
                whiteSpace: 'nowrap',
                minWidth: '70px',
                textAlign: 'right',
              }}
            >
              {displayTime} / {totalTime}
            </Typography>
          </Box>
        </Box>

        <IconButton
          onClick={togglePlay}
          disabled={isLoading}
          aria-label={getAudioButtonLabel(isLoading, isPlaying)}
          size="small"
        >
          {isLoading && (
            <CircularProgress
              color="inherit"
              sx={{ width: '24px !important', height: '24px !important' }}
            />
          )}
          {!isLoading && (
            <>
              {!isPlaying && <PlayIcon />}
              {isPlaying && <PauseIcon />}
            </>
          )}
        </IconButton>

        <IconButton
          onClick={() => window.open(src, '_blank', 'noopener,noreferrer')}
          size="small"
        >
          <DownloadIcon />
        </IconButton>
      </Box>
    </HugoThemeProvider>
  );
};

export default PostAudio;
