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

import Stack from '@material-hu/mui/Stack';

import InputSign from '@material-hu/components/composed-components/dynamic-forms/components/FormInputs/InputSign';

import { uploadFiles } from 'src/services/attachments';
import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = {
  name: string;
  required?: boolean;
  disabled?: boolean;
};

const getSignatureUrl = (value: unknown): string | null => {
  if (!value || typeof value !== 'object') return null;
  const obj = value as Record<string, unknown>;
  if (typeof obj.url === 'string') return obj.url;
  const answer = obj.answer as { url: string }[] | undefined;
  return answer?.[0]?.url ?? null;
};

const DigitalSignUploader = ({ name, required, disabled }: Props) => {
  const { t } = useLokaliseTranslation(['forms', 'general', 'validations']);
  const { control } = useFormContext();

  return (
    <Controller
      name={name}
      control={control}
      rules={{
        required: required && !disabled ? t('validations:required') : false,
      }}
      render={({ field: { value } }) => {
        const readOnlyUrl = disabled ? getSignatureUrl(value) : null;

        if (readOnlyUrl) {
          return (
            <Stack
              sx={{
                marginX: 'auto',
                height: '200px',
                width: '100%',
                borderRadius: ({ shape }) => shape.borderRadiusM,
                backgroundColor: theme =>
                  theme.palette.new.background.layout.default,
                overflow: 'hidden',
              }}
            >
              <img
                src={readOnlyUrl}
                alt="signature"
                style={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'contain',
                  aspectRatio: '2.8/1',
                }}
              />
            </Stack>
          );
        }

        return (
          <InputSign
            name={name}
            disabled={disabled}
            signProps={{
              uploadFn: uploadFiles,
            }}
            buttonProps={{
              children: t('forms:DIGITAL_SIGN_INPUT'),
            }}
            deleteButtonProps={{
              children: t('general:delete'),
            }}
            editButtonProps={{
              children: t('general:edit'),
            }}
          />
        );
      }}
    />
  );
};

export default DigitalSignUploader;
