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

import { IconInfoCircle, IconPlus } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Button from '@material-hu/components/design-system/Buttons/Button';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import FormSwitcher from '@material-hu/components/design-system/Switcher/form';

import { CERTIFICATE_MAX_LOGOS } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import {
  certificateCreateFields,
  emptyLogoSlot,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/form';
import { type CertificateCreateFormValues } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/types';
import {
  getValidLogoSlotsCount,
  isMaxLogoSlots,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/utils';
import { revokeBlobUrl } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CertificateLogoSlot from './CertificateLogoSlot';

const CertificateLogosSection = () => {
  const { t } = useLokaliseTranslation(['learning', 'service_management']);
  const { palette } = useTheme();
  const { control, setValue, getValues } =
    useFormContext<CertificateCreateFormValues>();

  const [logosEnabled, logoSlots] = useWatch({
    control,
    name: [
      certificateCreateFields.certificateLogosEnabled(),
      certificateCreateFields.logoSlots(),
    ],
  });

  const [visibleSlots, setVisibleSlots] = useState(() =>
    Math.max(1, getValidLogoSlotsCount(logoSlots)),
  );

  const handleAddSlot = () => {
    if (!isMaxLogoSlots(visibleSlots)) setVisibleSlots(prev => prev + 1);
  };

  const handleDeleteSlot = (indexToDelete: number) => {
    const currentSlots = getValues(certificateCreateFields.logoSlots());
    const deletedFile = currentSlots[indexToDelete]?.file?.[0]?.file;
    if (deletedFile) revokeBlobUrl(deletedFile);
    const newSlots = [...currentSlots] as typeof currentSlots;
    for (let i = indexToDelete; i < CERTIFICATE_MAX_LOGOS - 1; i++) {
      newSlots[i] = newSlots[i + 1];
    }
    newSlots[CERTIFICATE_MAX_LOGOS - 1] = emptyLogoSlot();
    setValue(certificateCreateFields.logoSlots(), newSlots);
    setVisibleSlots(prev => Math.max(1, prev - 1));
  };

  return (
    <CardContainer
      fullWidth
      sx={{
        '& .MuiCardContent-root': {
          display: 'flex',
          flexDirection: 'column',
          gap: 2,
          width: '100%',
        },
      }}
    >
      <Typography
        variant="globalS"
        sx={{
          fontWeight: 'fontWeightSemiBold',
          color: palette.new.text.neutral.lighter,
        }}
      >
        {t('settings.certificates.create_flow.logos')}
      </Typography>
      <FormSwitcher
        name={certificateCreateFields.certificateLogosEnabled()}
        switcherProps={{
          title: t('settings.certificates.create_flow.include_logos'),
          description: t(
            'settings.certificates.create_flow.include_logos_description',
          ),
        }}
      />
      {logosEnabled && (
        <Stack sx={{ gap: 3 }}>
          {Array.from({ length: visibleSlots }).map((_, i) => (
            <CertificateLogoSlot
              key={logoSlots[i]?.id}
              index={i}
              onDelete={() => handleDeleteSlot(i)}
            />
          ))}
          {isMaxLogoSlots(visibleSlots) && (
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 1,
                color: palette.new.text.neutral.lighter,
              }}
            >
              <IconInfoCircle size={20} />
              <Typography variant="globalXS">
                {t('settings.certificates.create_flow.logos_limit', {
                  limit: CERTIFICATE_MAX_LOGOS,
                })}
              </Typography>
            </Stack>
          )}
          <Button
            variant="tertiary"
            onClick={handleAddSlot}
            disabled={isMaxLogoSlots(visibleSlots)}
            startIcon={<IconPlus />}
            fullWidth
          >
            {t('settings.certificates.create_flow.add_logo')}
          </Button>
        </Stack>
      )}
    </CardContainer>
  );
};

export default CertificateLogosSection;
