import { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import SignComponent from 'react-signature-canvas';

import { useTheme } from '@mui/material';

import { type FileAsset, type FormFile } from 'types/attachments';

import HuCardContainer from '../../../../design-system/CardContainer';
import HuDialog from '../../../../design-system/Dialog';

export type SignProps = {
  disabled?: boolean;
  onClose?: () => void;
  onSave?: (signature: string | undefined) => void;
  title?: string;
  loading?: boolean;
  uploadFn?: (files: FormFile[]) => Promise<FileAsset[]>;
  minStrokes?: number;
};

const SignDialog = ({
  onClose,
  onSave,
  title,
  loading,
  disabled = false,
  minStrokes = 1,
}: SignProps) => {
  const { t } = useTranslation('material_hu_only');
  const theme = useTheme();
  const signRef = useRef<SignComponent | null>(null);
  const [hasMinimumStrokes, setHasMinimumStrokes] = useState(false);

  const handleSave = () => {
    const signature = signRef.current?.toDataURL();
    onSave?.(signature);
  };

  const handleClose = () => {
    onClose?.();
    signRef.current?.clear();
    setHasMinimumStrokes(false);
  };

  const onHandleEnd = () => {
    if (signRef.current) {
      const data = signRef.current.toData();

      const totalPoints = data.reduce((acc, stroke) => acc + stroke.length, 0);

      setHasMinimumStrokes(totalPoints >= minStrokes);
    }
  };

  const disabledToSign = !hasMinimumStrokes;

  return (
    <HuDialog
      onClose={handleClose}
      title={title || t('sign_dialog.title')}
      primaryButtonProps={{
        children: t('sign_dialog.sign'),
        variant: 'primary',
        onClick: handleSave,
        disabled: disabledToSign,
        loading,
      }}
      secondaryButtonProps={{
        children: t('sign_dialog.cancel'),
        variant: 'secondary',
        onClick: handleClose,
      }}
      body={
        <HuCardContainer
          padding={0}
          sx={{
            width: '99%',
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.default,
            opacity: disabled ? 0.5 : 1,
            pointerEvents: disabled ? 'none' : 'auto',
          }}
        >
          <SignComponent
            ref={signRef}
            onEnd={onHandleEnd}
            penColor={theme.palette.new.text.neutral.default}
            canvasProps={{
              style: {
                minHeight: 215,
                width: '100%',
                height: '100%',
              },
            }}
          />
        </HuCardContainer>
      }
    />
  );
};

export default SignDialog;
