import { type FC, useCallback, useId } from 'react';
import { useFormContext } from 'react-hook-form';

import { useFileAssetUploader } from '@material-hu/hooks/FileAssetUploader/useFileAssetUploader';
import {
  IconRefresh,
  IconSignature,
  IconTrash,
} from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';

import HuSignDialog from '@material-hu/components/composed-components/sign/documents/SignDialog';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuTooltip from '@material-hu/components/design-system/Tooltip';
import {
  useDialogLayer,
  useDialogLayerItem,
} from '@material-hu/components/layers/Dialogs';

import { type SectionComponent } from 'src/pages/dashboard/serviceManagement/types';
import { signedUploadWithOptions } from 'src/pages/dashboard/serviceManagement/utils';
import { base64ToFile } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { usePdfCompletion } from '../../contexts/PdfFormCompletionProvider';

import useFieldErrorMessages from './useFieldErrorMessages';

type SignatureInputProps = {
  field: SectionComponent;
  onChange: (values: unknown) => void;
  inputDigitalSign?: string;
  dimensions: {
    width: number;
    height: number;
  };
};

const SignatureField: FC<SignatureInputProps> = ({
  onChange,
  dimensions,
  field,
}) => {
  const {
    nameId: name,
    content: { required },
  } = field;

  const { t } = useLokaliseTranslation('service_management');
  const theme = useTheme();
  const { showErrors } = usePdfCompletion();

  const { setValue, watch, trigger } = useFormContext();
  const signatureValue = watch(name);

  const { hasErrors, getTooltipProps } = useFieldErrorMessages({
    showErrors,
    field,
    answer: signatureValue,
  });

  const pxDimensions = {
    width: dimensions?.width ? `${dimensions?.width}px` : undefined,
    height: dimensions?.height ? `${dimensions?.height}px` : undefined,
  };

  const dialogId = useId();
  const { closeDialog } = useDialogLayer();
  const closeSignModal = useCallback(
    () => closeDialog(dialogId),
    [closeDialog, dialogId],
  );

  const { uploadFiles, isLoading } = useFileAssetUploader(
    signedUploadWithOptions,
    {
      onSuccess: ([asset]) => {
        if (asset) {
          setValue(name, { id: asset.id, url: asset.url });
          trigger(name);
        }
        closeSignModal();
      },
    },
  );

  const handleOnCancel = () => {
    onChange(undefined);
    closeSignModal();
  };

  const handleAccept = useCallback(
    (signature: string | undefined) => {
      if (!signature) return;
      const file = base64ToFile(signature, 'signature.png');
      uploadFiles([file], { shouldCompress: false });
    },
    [uploadFiles],
  );

  const hasSigned = Boolean(signatureValue?.url);

  const { openDialog: showSignModal } = useDialogLayerItem(dialogId, {
    content: (
      <HuSignDialog
        onSave={handleAccept}
        onClose={closeSignModal}
        loading={isLoading}
      />
    ),
    onClose: closeSignModal,
    dialogProps: { fullWidth: true },
  });

  const buttonLabel = field.content.title || t('add_signature');

  return (
    <HuTooltip
      {...getTooltipProps()}
      disableTooltip={hasSigned}
    >
      <Stack
        onClick={() => showSignModal()}
        sx={{
          ...pxDimensions,
          backgroundColor: ({ palette }) =>
            hasErrors
              ? alpha(palette.new.background.feedback.error ?? '', 0.8)
              : alpha(palette.new.background.layout.brand ?? '', 0.8),
          justifyContent: 'center',
          cursor: 'pointer',
          alignItems: 'center',
          borderRadius: ({ shape }) => shape.borderRadiusM,
          '&:hover': {
            border: ({ palette }) =>
              `1px solid ${hasErrors ? palette.new.border.states.error : palette.new.border.neutral.brand}`,
          },
          ...(hasErrors && {
            border: ({ palette }) =>
              `1px solid ${palette.new.border.states.error}`,
          }),
          p: 1,
        }}
      >
        {!hasSigned && (
          <Button
            variant="tertiary"
            startIcon={
              <IconSignature color={theme.palette.new.text.neutral.default} />
            }
            sx={{
              ...(hasErrors && {
                color: ({ palette }) => palette.new.text.feedback.error,
              }),
              pointerEvents: 'none',
              maxWidth: '100%',
              minWidth: 0,
              justifyContent: 'center',
              overflow: 'hidden',
              width: '100%',
            }}
          >
            <span
              style={{
                minWidth: 0,
                maxWidth: '100%',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                display: 'inline-block',
              }}
            >
              {`${buttonLabel}${required ? ' *' : ''}`}
            </span>
          </Button>
        )}
        {hasSigned && (
          <Stack
            sx={{
              position: 'relative',
              borderRadius: ({ shape }) => shape.borderRadiusM,
              backgroundColor: ({ palette }) =>
                palette.new.background.layout.tertiary,
              border: ({ palette }) =>
                `1px solid ${palette.new.border.neutral.divider}`,
              '&:hover': {
                border: ({ palette }) =>
                  `1px solid ${palette.new.border.neutral.brand}`,
              },
              alignItems: 'center',
              justifyContent: 'center',
              ...pxDimensions,
            }}
          >
            <img
              alt="signature"
              src={signatureValue?.url}
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'fill',
              }}
            />
            <Stack
              sx={{
                position: 'absolute',
                top: '-26px',
                right: 0,
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <IconButton
                variant="tertiary-filled"
                size="small"
                onClick={e => {
                  e.stopPropagation();
                  showSignModal();
                }}
              >
                <IconRefresh />
              </IconButton>
              <IconButton
                variant="tertiary-filled"
                size="small"
                onClick={e => {
                  e.stopPropagation();
                  handleOnCancel();
                }}
              >
                <IconTrash />
              </IconButton>
            </Stack>
          </Stack>
        )}
      </Stack>
    </HuTooltip>
  );
};

export default SignatureField;
