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

import { IconPhotoEdit, IconTrash, IconX } 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 FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
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_SIGNATURES,
  CERTIFICATE_SIGNER_NAME_MAX_LENGTH,
  CERTIFICATE_SIGNER_TITLE_MAX_LENGTH,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import useDeleteSignatureDialog from 'src/pages/dashboard/Learning/Settings/Certificates/Create/hooks/useDeleteSignatureDialog';
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 CertificateSignatureSlotProps = {
  index: number;
  onDelete: () => void;
  canRemove: boolean;
};

const CertificateSignatureSlot = ({
  index,
  onDelete,
  canRemove,
}: CertificateSignatureSlotProps) => {
  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: `signatureSlots.${index}.file`,
  });

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

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

  const { openDeleteSignatureDialog } = useDeleteSignatureDialog({
    index,
    onDelete,
  });

  const optionalLabel = (label: string) =>
    `${label} (${t('general:optional')})`;

  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(`signatureSlots.${index}.file`, [fileCard]);
  };

  if (!hasFile) {
    return (
      <Stack sx={{ position: 'relative' }}>
        {canRemove && fileField.length === 0 && (
          <Tooltip title={t('general:delete')}>
            <IconButton
              aria-label={t('general:delete')}
              onClick={onDelete}
              sx={{ position: 'absolute', top: 8, right: 8, zIndex: 1 }}
            >
              <IconX size={20} />
            </IconButton>
          </Tooltip>
        )}
        <FormUploader
          name={`signatureSlots.${index}.file`}
          uploaderProps={{
            title: t('settings.certificates.create_flow.signature_upload', {
              current: index + 1,
              total: CERTIFICATE_MAX_SIGNATURES,
            }),
            description: t(
              'settings.certificates.create_flow.signature_upload_description',
              { maxSize: CERTIFICATE_DESIGN_IMAGE_MAX_MB },
            ),
            maxFiles: 1,
            acceptedTypes: ['image'],
            fileSizeLimit: CERTIFICATE_DESIGN_IMAGE_MAX_BYTES,
            uploadFunction: uploadCertificateImage,
            triggerOnChangeWhenUploading: true,
            showUploadButtonOnMaxFiles: false,
          }}
        />
      </Stack>
    );
  }

  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.signature_upload', {
                current: index + 1,
                total: CERTIFICATE_MAX_SIGNATURES,
              })}
            </Typography>
            <Stack sx={{ flexDirection: 'row', gap: 0.5 }}>
              <Tooltip title={t('general:change_signature')}>
                <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_signature')}
              >
                <span>
                  <IconButton
                    aria-label={t('general:delete')}
                    onClick={openDeleteSignatureDialog}
                    disabled={imageLoading || isUploading}
                  >
                    <IconTrash size={20} />
                  </IconButton>
                </span>
              </Tooltip>
            </Stack>
          </Stack>
          <Stack sx={{ flexDirection: 'row', gap: 3, alignItems: 'center' }}>
            <Image
              src={imageSrc}
              loading={imageLoading || isUploading}
              alt={t('settings.certificates.create_flow.signature')}
              sx={{
                height: 111,
                width: 156,
                objectFit: 'contain',
                flexShrink: 0,
              }}
            />
            <Stack sx={{ gap: 1.5, flex: 1 }}>
              <FormInputClassic
                name={`signatureSlots.${index}.signerName`}
                inputProps={{
                  label: optionalLabel(
                    t('settings.certificates.create_flow.signature_name'),
                  ),
                  placeholder: t(
                    'settings.certificates.create_flow.signature_name_placeholder',
                  ),
                  fullWidth: true,
                  maxLength: CERTIFICATE_SIGNER_NAME_MAX_LENGTH,
                  hasCounter: true,
                }}
              />
              <FormInputClassic
                name={`signatureSlots.${index}.signerTitle`}
                inputProps={{
                  label: optionalLabel(
                    t('settings.certificates.create_flow.signature_title'),
                  ),
                  placeholder: t(
                    'settings.certificates.create_flow.signature_title_placeholder',
                  ),
                  fullWidth: true,
                  maxLength: CERTIFICATE_SIGNER_TITLE_MAX_LENGTH,
                  hasCounter: true,
                }}
              />
            </Stack>
          </Stack>
        </Stack>
      </CardContainer>
    </>
  );
};

export default CertificateSignatureSlot;
