import { useRef, useState } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import { IconPhotoEdit, IconTrash } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Image from '@material-hu/components/composed-components/Image';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import { useSnackbar } from '@material-hu/components/design-system/Snackbar';
import Tooltip from '@material-hu/components/design-system/Tooltip';
import { typeMap } from '@material-hu/components/design-system/Uploader/constants';
import FormUploader from '@material-hu/components/design-system/Uploader/form';

import { useFileCardSrc } from 'src/hooks/useFileCardSrc';
import {
  CERTIFICATE_DESIGN_IMAGE_MAX_BYTES,
  CERTIFICATE_DESIGN_IMAGE_MAX_MB,
  CERTIFICATE_MAX_LOGOS,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import useDeleteLogoDialog from 'src/pages/dashboard/Learning/Settings/Certificates/Create/hooks/useDeleteLogoDialog';
import { type CertificateCreateFormValues } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/types';
import { uploadCertificateImage } from 'src/pages/dashboard/Learning/Settings/Certificates/utils';
import { revokeBlobUrl } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

type CertificateLogoSlotProps = {
  index: number;
  onDelete: () => void;
};

const CertificateLogoSlot = ({ index, onDelete }: CertificateLogoSlotProps) => {
  const { t } = useLokaliseTranslation(['learning', 'service_management']);
  const { control, setValue } = useFormContext<CertificateCreateFormValues>();
  const { palette } = useTheme();
  const { enqueueSnackbar } = useSnackbar();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isUploading, setIsUploading] = useState(false);

  const fileField = useWatch({
    control,
    name: `logoSlots.${index}.file`,
  });

  const hasFile = fileField.some(fileCard => fileCard.status !== 'uploading');

  const { src: imageSrc, loading: imageLoading } = useFileCardSrc(fileField);

  const { openDeleteLogoDialog } = useDeleteLogoDialog({ index, onDelete });

  const handleReplaceFile = () => {
    fileInputRef.current?.click();
  };

  const handleFileInputChange = async (
    e: React.ChangeEvent<HTMLInputElement>,
  ) => {
    const file = e.target.files?.[0];
    e.target.value = '';
    if (!file) return;
    if (file.size > CERTIFICATE_DESIGN_IMAGE_MAX_BYTES) {
      enqueueSnackbar({
        title: t('service_management:file_size_rejected', {
          size: `${CERTIFICATE_DESIGN_IMAGE_MAX_MB} MB`,
        }),
        variant: 'error',
      });
      return;
    }
    setIsUploading(true);
    const fileCard = await uploadCertificateImage(file);
    setIsUploading(false);
    if (fileCard.status === 'error') {
      enqueueSnackbar({
        title: t('general:error_title'),
        description: t('general:retry_later'),
        variant: 'error',
      });
      return;
    }
    const oldFile = fileField[0]?.file;
    if (oldFile) revokeBlobUrl(oldFile);
    setValue(`logoSlots.${index}.file`, [fileCard]);
  };

  if (!hasFile) {
    return (
      <FormUploader
        name={`logoSlots.${index}.file`}
        uploaderProps={{
          title: t('settings.certificates.create_flow.logos_upload', {
            current: index + 1,
            total: CERTIFICATE_MAX_LOGOS,
          }),
          description: t(
            'settings.certificates.create_flow.logos_upload_description',
            { maxSize: CERTIFICATE_DESIGN_IMAGE_MAX_MB },
          ),
          maxFiles: 1,
          acceptedTypes: ['image'],
          fileSizeLimit: CERTIFICATE_DESIGN_IMAGE_MAX_BYTES,
          uploadFunction: uploadCertificateImage,
          triggerOnChangeWhenUploading: true,
          showUploadButtonOnMaxFiles: false,
        }}
      />
    );
  }

  return (
    <>
      <input
        ref={fileInputRef}
        type="file"
        accept={typeMap['image'].extensions.join(',')}
        style={{ display: 'none' }}
        onChange={handleFileInputChange}
      />
      <CardContainer
        color="grey"
        fullWidth
      >
        <Stack sx={{ gap: 2 }}>
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <Typography
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              color={palette.new.text.neutral.lighter}
            >
              {t('settings.certificates.create_flow.logos_upload', {
                current: index + 1,
                total: CERTIFICATE_MAX_LOGOS,
              })}
            </Typography>
            <Stack sx={{ flexDirection: 'row', gap: 0.5 }}>
              <Tooltip
                title={t('settings.certificates.create_flow.logo_change')}
              >
                <span>
                  <IconButton
                    aria-label={t('general:edit')}
                    onClick={handleReplaceFile}
                    disabled={imageLoading || isUploading}
                  >
                    <IconPhotoEdit size={20} />
                  </IconButton>
                </span>
              </Tooltip>
              <Tooltip
                title={t('settings.certificates.create_flow.delete_logo')}
              >
                <span>
                  <IconButton
                    aria-label={t('general:delete')}
                    onClick={openDeleteLogoDialog}
                    disabled={imageLoading || isUploading}
                  >
                    <IconTrash size={20} />
                  </IconButton>
                </span>
              </Tooltip>
            </Stack>
          </Stack>
          <Image
            src={imageSrc}
            loading={imageLoading || isUploading}
            alt={t('settings.certificates.create_flow.logos')}
            sx={{
              height: 81,
              width: 163,
              objectFit: 'contain',
              alignSelf: 'center',
            }}
          />
        </Stack>
      </CardContainer>
    </>
  );
};

export default CertificateLogoSlot;
