import { useState } from 'react';

import {
  IconArrowBigRightLines,
  IconCalendarShare,
  IconClipboardText,
  IconDownload,
  IconInfoCircle,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Avatar from '@material-hu/components/design-system/Avatar';
import Spinner from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import { Title } from '@material-hu/components/design-system/Title';

import useGeneralError from 'src/hooks/useGeneralError';
import RichText from 'src/pages/dashboard/performance/components/RichText';
import { downloadSurveyResponse } from 'src/services/surveys';
import { type FormAttributes } from 'src/types/forms';
import { getBlobUrl, openBlob } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = {
  formData: FormAttributes;
};

const SIDEBAR_WIDTH = ['200px', '240px', '288px'];
export const SIDEBAR_INFO_WIDTH = '73px';

const CompletedSurveyInfoSidebar = ({ formData }: Props) => {
  const { t } = useLokaliseTranslation(['surveys', 'forms']);
  const showGeneralError = useGeneralError();

  const [isLoadingDownload, setIsLoadingDownload] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);

  const sendDate = new Date(formData.createdAt).toLocaleDateString('es', {
    day: '2-digit',
    month: 'short',
    year: '2-digit',
  });

  const handleDownloadSurveyResponse = async () => {
    if (!formData.templateId || !formData.id) return;
    try {
      setIsLoadingDownload(true);

      const reportData = await downloadSurveyResponse(
        formData.templateId,
        formData.id,
      );

      const blob = new Blob([reportData.data], { type: 'application/pdf' });
      const blobUrl = getBlobUrl(blob);

      openBlob(blob, blobUrl ?? '');
    } catch (err) {
      showGeneralError(err, t('forms:error_loading_pdf_report'));
    } finally {
      setIsLoadingDownload(false);
    }
  };

  return (
    <Stack sx={{ flexDirection: 'row', flexShrink: 0, height: 1 }}>
      {isExpanded && (
        <Stack
          sx={{
            width: SIDEBAR_WIDTH,
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.tertiary,
            borderLeft: ({ palette }) =>
              `1px solid ${palette.new.border.neutral.default}`,
            overflowY: 'auto',
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              p: 2,
              gap: 1,
            }}
          >
            <IconButton
              variant="secondary"
              onClick={() => setIsExpanded(false)}
            >
              <IconArrowBigRightLines size={24} />
            </IconButton>
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              sx={{ color: ({ palette }) => palette.new.text.neutral.default }}
            >
              {t('more_info')}
            </Typography>
          </Stack>
          <Stack sx={{ px: 3, py: 2, gap: 3 }}>
            <Stack sx={{ gap: 3 }}>
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}
              >
                <Avatar
                  color="primary"
                  Icon={IconClipboardText}
                  size="small"
                />
                <Title
                  variant="S"
                  title={formData.title}
                  copetin={`#${formData.id}`}
                />
              </Stack>
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}
              >
                <Avatar
                  color="primary"
                  Icon={IconCalendarShare}
                  size="small"
                />
                <Title
                  variant="S"
                  title={sendDate}
                  copetin={t('surveys:send_date')}
                />
              </Stack>
            </Stack>
            <Divider />
            {formData.autoMessage && (
              <RichText
                text={formData.autoMessage}
                sx={{
                  wordBreak: 'break-word',
                  overflowWrap: 'break-word',
                  fontSize: 'globalXS.fontSize',
                }}
              />
            )}
          </Stack>
        </Stack>
      )}
      <Stack
        sx={{
          alignItems: 'center',
          gap: 2,
          p: 2,
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.tertiary,
          borderLeft: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.divider}`,
        }}
      >
        <IconButton
          variant={isExpanded ? 'tertiary-filled' : 'tertiary'}
          onClick={() => setIsExpanded(prev => !prev)}
        >
          <IconInfoCircle size={24} />
        </IconButton>
        <IconButton
          variant="tertiary"
          onClick={handleDownloadSurveyResponse}
        >
          {isLoadingDownload && <Spinner size={24} />}
          {!isLoadingDownload && <IconDownload size={24} />}
        </IconButton>
      </Stack>
    </Stack>
  );
};

export default CompletedSurveyInfoSidebar;
