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

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

import useAuth from 'src/contexts/JWTContext';
import { useFileCardSrc } from 'src/hooks/useFileCardSrc';
import { certificateCreateFields } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/form';
import { type CertificateCreateFormValues } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/types';
import {
  getCertificateAccentHex,
  mapLogoSlots,
  mapSignatureSlots,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/utils';
import { CertificateAlignment } from 'src/pages/dashboard/Learning/Settings/Certificates/constants';
import { getFullname } from 'src/utils/userUtils';

import CertificatePreviewCanvas from '../CertificatePreviewCanvas';

const CertificatePreviewForm = () => {
  const { control } = useFormContext<CertificateCreateFormValues>();
  const theme = useTheme();
  const { user, instance } = useAuth();

  const [
    templateId,
    accentColor,
    headingTitle,
    subtitle,
    description,
    textAlignment,
    signaturesEnabled,
    signatureSlots,
    logosEnabled,
    logoSlots,
    customBackgroundFile,
  ] = useWatch({
    control,
    name: [
      certificateCreateFields.type(),
      certificateCreateFields.color(),
      certificateCreateFields.title(),
      certificateCreateFields.subtitle(),
      certificateCreateFields.description(),
      certificateCreateFields.alignment(),
      certificateCreateFields.certificateSignaturesEnabled(),
      certificateCreateFields.signatureSlots(),
      certificateCreateFields.certificateLogosEnabled(),
      certificateCreateFields.logoSlots(),
      certificateCreateFields.certificateCustomBackgroundFile(),
    ],
  });

  const accentHex = getCertificateAccentHex(
    accentColor,
    theme,
    instance?.color,
  );

  const recipientName = getFullname(user ?? undefined);

  const { src: backgroundImageUrl } = useFileCardSrc(customBackgroundFile);

  const signatures = mapSignatureSlots(signatureSlots);
  const logos = mapLogoSlots(logoSlots);

  return (
    <CertificatePreviewCanvas
      templateId={templateId}
      accentColor={accentColor}
      accentHex={accentHex}
      recipientName={recipientName}
      headingTitle={headingTitle ?? ''}
      subtitle={subtitle ?? ''}
      description={description ?? ''}
      textAlignment={textAlignment ?? CertificateAlignment.CENTER}
      signaturesEnabled={signaturesEnabled}
      signatures={signatures}
      logosEnabled={logosEnabled}
      logos={logos}
      backgroundImageUrl={backgroundImageUrl}
    />
  );
};

export default CertificatePreviewForm;
