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

import { type DynamicFormValues } from '@composed-components/dynamic-forms/types';
import { isFileAsset } from '@composed-components/dynamic-forms/utils/extraUtils';
import FormSign from '@composed-components/sign/documents/SignDialog/form';
import { type FormSignProps } from '@composed-components/sign/documents/SignDialog/types';
import Button, { type ButtonProps } from '@design-system/Buttons/Button';
import { useModal } from '@hooks/useModal';
import FormHelperText from '@mui/material/FormHelperText';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import {
  IconExclamationCircle,
  IconSignature,
  IconTrash,
} from '@tabler/icons-react';
import { processFile } from '@utils/attachments';
import { urlToFile } from '@utils/files';

export type InputSignProps = {
  name: string;
  disabled?: boolean;
  buttonProps?: ButtonProps;
  deleteButtonProps?: Partial<ButtonProps>;
  editButtonProps?: Partial<ButtonProps>;
  signProps?: FormSignProps['signProps'];
};

const InputSign = ({
  name,
  disabled,
  buttonProps,
  deleteButtonProps,
  editButtonProps,
  signProps,
}: InputSignProps) => {
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const { setValue: setFormValue, control } =
    useFormContext<DynamicFormValues>();

  const { fieldState, field } = useController({ name, control: control });

  const handleSaveFileAsset = async (newSignature: string | undefined) => {
    signModal.closeModal();

    if (!newSignature) return;

    if (!signProps?.uploadFn) {
      throw new Error('uploadFn is required');
    }

    setPreviewUrl(newSignature);

    // Convert the new signature to a file
    const signatureFile = await urlToFile(newSignature);

    // Process the file to get the correct type
    const processedSignature = await processFile(signatureFile);

    // Upload the file to S3
    const [uploadedFile] = await signProps?.uploadFn?.([processedSignature]);

    signProps?.onSave?.(newSignature);

    setFormValue(name, uploadedFile, { shouldValidate: true });
  };

  const signModal = useModal(
    FormSign,
    { fullWidth: true },
    {
      name,
      disabled,
      signProps: {
        ...signProps,
        onSave: handleSaveFileAsset,
        onClose: () => {
          signModal.closeModal();
          signProps?.onClose?.();
        },
      },
    },
  );

  const urlToDisplay =
    previewUrl || (isFileAsset(field.value) ? field.value.url : null);
  return (
    <>
      {urlToDisplay && (
        <Stack
          sx={{
            marginX: 'auto',
            height: '200px',
            width: '100%',
            borderRadius: '8px',
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
            overflow: 'hidden',
            mb: 2,
            position: 'relative',
          }}
        >
          <img
            src={urlToDisplay}
            alt="signature"
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'contain',
              aspectRatio: '2.8/1',
            }}
          />
          <Stack
            sx={{
              position: 'absolute',
              top: 8,
              right: 8,
              flexDirection: 'row',
              gap: 1,
            }}
          >
            <Button
              variant="tertiary"
              size="small"
              disabled={disabled}
              onClick={() => {
                setFormValue(name, null, { shouldValidate: true });
                setPreviewUrl(null);
              }}
              startIcon={
                !deleteButtonProps?.startIcon &&
                !deleteButtonProps?.children && <IconTrash />
              }
              {...deleteButtonProps}
            />
            <Button
              variant="secondary"
              size="small"
              onClick={() => signModal.showModal()}
              disabled={disabled}
              startIcon={
                !editButtonProps?.startIcon &&
                !editButtonProps?.children && <IconSignature />
              }
              {...editButtonProps}
            />
          </Stack>
        </Stack>
      )}
      {!urlToDisplay && (
        <Button
          onClick={() => signModal.showModal()}
          disabled={disabled}
          variant="secondary"
          size="large"
          endIcon={<IconSignature />}
          sx={{
            display: 'flex',
            marginX: 'auto',
            ...buttonProps?.sx,
          }}
          {...buttonProps}
        />
      )}
      <FormHelperText
        sx={{
          mx: 0,
          '& *': {
            color: theme => `${theme.palette.textColors?.errorText} !important`,
          },
        }}
      >
        <Stack
          component="span"
          sx={{ alignItems: 'center', flexDirection: 'row', gap: 0.5 }}
        >
          {fieldState.error?.message && (
            <>
              {fieldState.error && <IconExclamationCircle size="1rem" />}
              <Typography variant="globalS">
                {fieldState.error?.message}
              </Typography>
            </>
          )}
        </Stack>
      </FormHelperText>
      {signModal.modal}
    </>
  );
};

export default InputSign;
