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_SIGNATURES } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';
import {
  certificateCreateFields,
  emptySignatureSlot,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/form';
import { type CertificateCreateFormValues } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/types';
import {
  getValidSignatureSlotsCount,
  isMaxSignatureSlots,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/utils';
import { revokeBlobUrl } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CertificateSignatureSlot from './CertificateSignatureSlot';

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

  const [signaturesEnabled, signatureSlots] = useWatch({
    control,
    name: [
      certificateCreateFields.certificateSignaturesEnabled(),
      certificateCreateFields.signatureSlots(),
    ],
  });

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

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

  const handleDeleteSlot = (indexToDelete: number) => {
    const currentSlots = getValues(certificateCreateFields.signatureSlots());
    const deletedFile = currentSlots[indexToDelete]?.file?.[0]?.file;
    if (deletedFile) revokeBlobUrl(deletedFile);
    const newSlots = [...currentSlots] as typeof currentSlots;
    for (let i = indexToDelete; i < CERTIFICATE_MAX_SIGNATURES - 1; i++) {
      newSlots[i] = newSlots[i + 1];
    }
    newSlots[CERTIFICATE_MAX_SIGNATURES - 1] = emptySignatureSlot();
    setValue(certificateCreateFields.signatureSlots(), 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.signature')}
      </Typography>
      <FormSwitcher
        name={certificateCreateFields.certificateSignaturesEnabled()}
        switcherProps={{
          title: t('settings.certificates.create_flow.include_signatures'),
          description: t(
            'settings.certificates.create_flow.include_signatures_description',
          ),
        }}
      />
      {signaturesEnabled && (
        <Stack sx={{ gap: 2 }}>
          {Array.from({ length: visibleSlots }).map((_, i) => (
            <CertificateSignatureSlot
              key={signatureSlots[i]?.id}
              index={i}
              onDelete={() => handleDeleteSlot(i)}
              canRemove={visibleSlots > 1}
            />
          ))}
          {isMaxSignatureSlots(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.signature_limit', {
                  limit: CERTIFICATE_MAX_SIGNATURES,
                })}
              </Typography>
            </Stack>
          )}
          <Button
            variant="tertiary"
            onClick={handleAddSlot}
            disabled={isMaxSignatureSlots(visibleSlots)}
            startIcon={<IconPlus />}
            fullWidth
          >
            {t('settings.certificates.create_flow.add_signature')}
          </Button>
        </Stack>
      )}
    </CardContainer>
  );
};

export default CertificateSignaturesSection;
