import { useRef } from 'react';
import QRCode from 'react-qr-code';

import IconButton from '@mui/material/IconButton';
import { useModal } from '@material-hu/hooks/useModal';
import {
  IconBrandLinkedin,
  IconBrandWhatsapp,
  IconCopy,
  IconDownload,
  IconMail,
} from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import Dialog from '@material-hu/components/design-system/Dialog';
import InputClassic from '@material-hu/components/design-system/Inputs/Classic';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';
import Title from '@material-hu/components/design-system/Title';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { useJobPublicDescription } from '../../hooks/useJobPublicDescription';

type UseShareJobModalProps = {
  url: string;
  jobId?: number | null;
  jobBoardName: string;
  isCareersSite?: boolean;
};

export const useShareJobModal = ({
  url,
  jobId,
  jobBoardName,
  isCareersSite = false,
}: UseShareJobModalProps) => {
  const { t } = useLokaliseTranslation(['ats', 'general']);
  const qrRef = useRef<HTMLDivElement>(null);
  const { enqueueSnackbar } = useHuSnackbar();

  // Only fetch the public description when sharing a specific job posting.
  const { publicDescription } = useJobPublicDescription(
    isCareersSite ? null : jobId,
  );

  const translationScope = isCareersSite
    ? 'job_offers.list.share_careers_site.share_modal'
    : 'job_offers.detail.share_modal';

  const handleDownload = async (type: 'svg' | 'png') => {
    const svg = qrRef.current?.querySelector('svg');
    if (!svg) return;
    const fileName = isCareersSite
      ? `qr-code-careers-site.${type}`
      : `qr-code-job-${jobId}.${type}`;

    if (type === 'svg') {
      const blob = new Blob([svg.outerHTML], { type: 'image/svg+xml' });
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = fileName;
      a.click();
      return;
    }

    const { width, height } = svg.getBoundingClientRect();

    const canvas = document.createElement('canvas');
    const scale = 3;
    canvas.width = width * scale;
    canvas.height = height * scale;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    ctx.scale(scale, scale);

    const img = new Image();
    const svgBlob = new Blob([svg.outerHTML], {
      type: 'image/svg+xml;charset=utf-8',
    });

    const url = URL.createObjectURL(svgBlob);
    img.src = url;

    await new Promise<void>(resolve => {
      img.onload = () => resolve();
    });

    ctx.drawImage(img, 0, 0, width, height);

    const a = document.createElement('a');
    a.href = canvas.toDataURL('image/png');
    a.download = fileName;
    a.click();
  };

  const handleCopy = () => {
    navigator.clipboard.writeText(url);
    enqueueSnackbar({ title: t('common.link_copied'), variant: 'success' });
  };

  type ShareNetwork = 'linkedIn' | 'email' | 'whatsapp';

  const SHARE_CONFIG: Record<
    ShareNetwork,
    {
      messageKey: string;
      buildUrl: (encodedText: string) => string;
    }
  > = {
    linkedIn: {
      messageKey: 'message_linkedIn',
      buildUrl: text =>
        `https://www.linkedin.com/shareArticle?url=${encodeURIComponent(
          url,
        )}&text=${text}`,
    },
    whatsapp: {
      messageKey: 'message_whatsapp',
      buildUrl: text => `https://wa.me/?text=${text}`,
    },
    email: {
      messageKey: 'message_email',
      buildUrl: text => {
        const getEmailSubject = () => {
          if (isCareersSite) {
            return jobBoardName
              ? t(`${translationScope}.email_subject`, { jobBoardName })
              : t(`${translationScope}.email_subject_fallback`);
          }

          return publicDescription?.title
            ? t(`${translationScope}.email_subject`, {
                jobTitle: publicDescription.title,
                jobBoardName,
              })
            : t(`${translationScope}.email_subject_fallback`);
        };

        return `mailto:?subject=${encodeURIComponent(getEmailSubject())}&body=${text}`;
      },
    },
  };

  const handleShareInNetwork = (network: ShareNetwork) => {
    const config = SHARE_CONFIG[network];

    const rawText = t(`${translationScope}.${config.messageKey}`, {
      url,
    });

    const encodedText = encodeURIComponent(rawText);

    window.open(config.buildUrl(encodedText), '_blank');
  };

  const networks = [
    {
      label: 'LinkedIn',
      Icon: IconBrandLinkedin,
      onClick: () => handleShareInNetwork('linkedIn'),
    },
    {
      label: t('common.email_short'),
      Icon: IconMail,
      onClick: () => handleShareInNetwork('email'),
    },
    {
      label: 'WhatsApp',
      Icon: IconBrandWhatsapp,
      onClick: () => handleShareInNetwork('whatsapp'),
    },
  ];

  const { closeModal, ...modalProps } = useModal(
    Dialog,
    {
      fullWidth: true,
      sx: {
        '& .MuiDialogContent-root': {
          maxHeight: 'unset',
        },
      },
    },
    {
      title: isCareersSite
        ? t('general:share')
        : t('job_offers.detail.share_modal.title'),
      body: (
        <Stack sx={{ gap: 3 }}>
          <Stack sx={{ flexDirection: 'row', gap: 3 }}>
            <InputClassic
              label={t('job_offers.detail.share_modal.public_url')}
              value={url}
              showClear={false}
              onChange={undefined}
              hasCounter={false}
            />
            <Stack
              sx={{
                alignSelf: 'end',
                alignItems: 'center',
                justifyContent: 'center',
                p: 2,
                width: 40,
                height: 40,
                mb: 1,
              }}
            >
              <IconButton
                size="small"
                sx={{ p: 1, width: 40, height: 40 }}
                variant="secondary"
                onClick={handleCopy}
              >
                <IconCopy />
              </IconButton>
            </Stack>
          </Stack>
          <Stack sx={{ flexDirection: 'row', gap: 3 }}>
            <Stack sx={{ flexDirection: 'column', gap: 1 }}>
              <Title
                variant="S"
                title={t('common.qr_code')}
              />
              <Stack
                ref={qrRef}
                sx={{
                  backgroundColor: 'white',
                  p: 2,
                  width: 130,
                  height: 130,
                  borderRadius: theme => theme.shape.borderRadiusM,
                  border: theme =>
                    `1px solid ${theme.palette.new.border.neutral.default}`,
                }}
              >
                <QRCode
                  value={url}
                  bgColor="white"
                  style={{ height: 'auto', maxWidth: '100%', width: '100%' }}
                />
              </Stack>
            </Stack>
            <Stack
              sx={{ flexDirection: 'column', gap: 3, justifyContent: 'center' }}
            >
              <Button
                variant="secondary"
                startIcon={<IconDownload />}
                onClick={() => handleDownload('png')}
              >
                {t('common.download_png')}
              </Button>
              <Button
                variant="secondary"
                startIcon={<IconDownload />}
                onClick={() => handleDownload('svg')}
              >
                {t('common.download_svg')}
              </Button>
            </Stack>
          </Stack>
          <Stack
            sx={{
              flexDirection: 'column',
              gap: 1,
              justifyContent: 'center',
              alignItems: 'start',
            }}
          >
            <Title
              variant="S"
              title={t('common.share_in_networks')}
            />
            <Stack sx={{ flexDirection: 'row', gap: 1 }}>
              {networks.map(({ label, Icon, onClick }) => (
                <ButtonBase
                  key={label}
                  onClick={onClick}
                  sx={{
                    flex: 1,
                    p: 0.5,
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    gap: 0.25,
                    minWidth: 82,
                    borderRadius: theme => theme.shape.borderRadiusM,
                    '&:hover': {
                      backgroundColor: theme =>
                        theme.palette.newBase?.brand[50],
                    },
                  }}
                >
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      width: 40,
                      height: 40,
                      color: theme => theme.palette.newBase?.brand[900],
                    }}
                  >
                    <Icon
                      size={24}
                      color="currentColor"
                    />
                  </Box>
                  <Typography variant="globalXXS">{label}</Typography>
                </ButtonBase>
              ))}
            </Stack>
          </Stack>
        </Stack>
      ),
    },
  );

  return { ...modalProps, closeModal };
};
