import { type MutableRefObject, useRef, useState } from 'react';
import {
  Controller,
  type UseControllerProps,
  useFormContext,
} from 'react-hook-form';
import { useMutation } from 'react-query';

import { useModal } from '@material-hu/hooks/useModal';

import { uploadSignature } from 'src/services/attachments';

import SignCard from './SignCard';
import SignDialog from './SignDialog';

export type HuFormSignProps = UseControllerProps & {
  onChange?: (value: string) => void;
  disabled?: boolean;
};

export const HuFormSign = ({
  name,
  disabled,
  onChange = () => null,
  ...controllerProps
}: HuFormSignProps) => {
  const [src, setSrc] = useState('');

  const digitalSignRef = useRef() as MutableRefObject<any>;

  const { control, setValue, trigger } = useFormContext();

  const clearSign = () => {
    if (!digitalSignRef.current) return;
    digitalSignRef.current.clear();
  };

  const resetSign = () => {
    if (!digitalSignRef.current) return;
    clearSign();
    digitalSignRef.current.fromDataURL(src);
  };

  const getSign = () => {
    if (!digitalSignRef.current) return '';
    return digitalSignRef.current.getCanvas().toDataURL('image/png');
  };

  const handleChange = (newValue: string) => {
    setSrc(newValue ? getSign() : '');
    onChange(newValue);
    setValue(name, newValue);
    trigger(name);
  };

  const uploadMutation = useMutation(
    (signature: string) => uploadSignature(signature),
    {
      onSuccess: response => {
        handleChange(response);
        closeModal();
      },
    },
  );

  const handleInputCancel = () => {
    resetSign();
    closeModal();
  };

  const handleDelete = () => {
    clearSign();
    handleChange('');
  };

  const handleChangeSign = () => {
    showModal();
  };

  const handleInputAccept = () => uploadMutation.mutate(getSign().slice(22));

  const handleAddSignature = () => showModal();

  const { modal, showModal, closeModal } = useModal(
    SignDialog,
    {
      keepMounted: true,
      sx: {
        '& .MuiPaper-root': {
          width: '50%',
          height: '50%',
          '& > .MuiStack-root': {
            width: '100%',
            height: '100%',
          },
        },
      },
    },
    {
      onCancel: handleInputCancel,
      onAccept: handleInputAccept,
      signRef: digitalSignRef,
      loading: uploadMutation.isLoading,
      isEdit: !!src,
    },
  );

  return (
    <Controller
      name={name}
      control={control}
      disabled={disabled}
      render={() => (
        <>
          {modal}
          <SignCard
            src={src}
            disabled={disabled}
            onDelete={handleDelete}
            onAdd={handleAddSignature}
            onChange={handleChangeSign}
          />
        </>
      )}
      {...controllerProps}
    />
  );
};

export default HuFormSign;
