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

import { useTheme } from '@material-hu/mui/styles';

import Alert from '@material-hu/components/design-system/Alert';
import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import Title from '@material-hu/components/design-system/Title';
import FormUploader from '@material-hu/components/design-system/Uploader/form';

import CertificatePreviewForm from 'src/pages/dashboard/Learning/Settings/Certificates/Create/components/CertificatePreviewForm';
import { CERTIFICATE_DESIGN_IMAGE_MAX_BYTES } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import { useCertificateCreateSteps } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/contexts/CertificateCreateStepsContext';
import { certificateCreateFields } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/form';
import { type CertificateCreateFormValues } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/types';
import { hasBackgroundFile } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/utils';
import { CertificateType } from 'src/pages/dashboard/Learning/Settings/Certificates/constants';
import { uploadCertificateImage } from 'src/pages/dashboard/Learning/Settings/Certificates/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

const CertificatePreview = () => {
  const { t } = useLokaliseTranslation('learning');
  const { palette } = useTheme();
  const { control, setValue } = useFormContext<CertificateCreateFormValues>();
  const {
    showCustomBackgroundError,
    setCustomBackgroundError,
    clearCustomBackgroundError,
  } = useCertificateCreateSteps();

  const [type, certificateCustomBackgroundFile] = useWatch({
    control,
    name: [
      certificateCreateFields.type(),
      certificateCreateFields.certificateCustomBackgroundFile(),
    ],
  });

  const hasCustomBackgroundImage = hasBackgroundFile(
    certificateCustomBackgroundFile,
  );

  const isCustomTemplate = type === CertificateType.CUSTOM_BACKGROUND;
  const showUploader = isCustomTemplate && !hasCustomBackgroundImage;
  const showChangeBackground = isCustomTemplate && hasCustomBackgroundImage;

  const bgFileInputRef = useRef<HTMLInputElement>(null);
  const [isUploading, setIsUploading] = useState(false);

  const handleChangeBgFile = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (!file) return;
      e.target.value = '';
      setIsUploading(true);
      const fileCard = await uploadCertificateImage(file);
      setIsUploading(false);
      if (fileCard.status === 'error') {
        setCustomBackgroundError(true);
        return;
      }
      setValue(
        certificateCreateFields.certificateCustomBackgroundFile(),
        [fileCard],
        { shouldDirty: true },
      );
    },
    [setValue, setCustomBackgroundError],
  );

  return (
    <>
      <CardContainer fullWidth>
        <Title
          variant="M"
          title={t('common.preview')}
          description={t(
            'settings.certificates.create_flow.preview_description',
          )}
        />
        {showUploader && (
          <FormUploader
            name={certificateCreateFields.certificateCustomBackgroundFile()}
            uploaderProps={{
              title: t(
                'settings.certificates.create_flow.personalized_background',
              ),
              description: t(
                'settings.certificates.create_flow.logos_upload_description',
                { maxSize: 50 },
              ),
              maxFiles: 1,
              acceptedTypes: ['image'],
              fileSizeLimit: CERTIFICATE_DESIGN_IMAGE_MAX_BYTES,
              uploadFunction: uploadCertificateImage,
              triggerOnChangeWhenUploading: true,
              showUploadButtonOnMaxFiles: false,
              sx: {
                mt: 2,
                width: '100%',
                '& .MuiStack-root[role="presentation"]': {
                  backgroundColor: palette.new.background.layout.tertiary,
                },
              },
              slotProps: {
                fileCard: { showReuploadButton: false },
              },
            }}
          />
        )}
        {!showUploader && (
          <>
            <CardContainer
              color="grey"
              fullWidth
              padding={16}
              sx={{ mt: 3 }}
            >
              <CertificatePreviewForm />
            </CardContainer>
            {showChangeBackground && (
              <>
                <input
                  ref={bgFileInputRef}
                  type="file"
                  accept="image/*"
                  style={{ display: 'none' }}
                  onChange={handleChangeBgFile}
                />
                <Button
                  variant="tertiary"
                  onClick={() => bgFileInputRef.current?.click()}
                  loading={isUploading}
                  disabled={isUploading}
                  sx={{ alignSelf: 'flex-start', mt: 1 }}
                >
                  {t('settings.certificates.create_flow.change_background')}
                </Button>
              </>
            )}
          </>
        )}
      </CardContainer>
      {showUploader && (
        <Alert
          severity="highlight"
          title={t(
            'settings.certificates.create_flow.personalized_background_advice',
          )}
          description={t(
            'settings.certificates.create_flow.info_alert_description',
          )}
        />
      )}
      {showCustomBackgroundError && (
        <Alert
          severity="error"
          title={t(
            'settings.certificates.create_flow.personalized_background_error',
          )}
          onClose={clearCustomBackgroundError}
        />
      )}
    </>
  );
};

export default CertificatePreview;
