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

import Stack from '@material-hu/mui/Stack';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import Title from '@material-hu/components/design-system/Title';

import { certificateTemplateOptions } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import { type CertificateCreateFormValues } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import CertificateTemplateAlert from './components/CertificateTemplateAlert';
import CertificateTemplateOptionCard from './components/CertificateTemplateOptionCard';

const TemplateStep = () => {
  const { t } = useLokaliseTranslation('learning');
  const { control, setValue } = useFormContext<CertificateCreateFormValues>();
  const type = useWatch({ control, name: 'type' });

  const handleSelectTemplate = (
    selectedType: CertificateCreateFormValues['type'],
  ) => {
    setValue('type', selectedType, { shouldDirty: true, shouldTouch: true });
    logEvent(LogEvents.CERTIFICATE_TEMPLATE_SELECTED, {
      templateType: selectedType,
    });
  };

  return (
    <Stack sx={{ gap: 2, width: '100%' }}>
      <CardContainer fullWidth>
        <Title
          variant="M"
          title={t('settings.certificates.create_flow.select_template')}
          description={t(
            'settings.certificates.create_flow.select_template_description',
          )}
        />
        <Stack
          sx={{
            flexDirection: { xs: 'column', md: 'row' },
            gap: 2,
            mt: 3,
            width: '100%',
          }}
        >
          {certificateTemplateOptions.map(option => (
            <CertificateTemplateOptionCard
              key={option.type}
              slug={option.slug}
              Image={option.Image}
              checked={type === option.type}
              onClick={() => handleSelectTemplate(option.type)}
            />
          ))}
        </Stack>
      </CardContainer>
      <CertificateTemplateAlert type={type} />
    </Stack>
  );
};

export default TemplateStep;
