import { useEffect, useId, useRef } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { type ButtonProps } from '@material-hu/components/design-system/Buttons/Button';
import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import {
  useDialogLayer,
  useDialogLayerItem,
} from '@material-hu/components/layers/Dialogs';

import { useLokaliseTranslation } from 'src/utils/i18n';

type CustomButtonProps = Omit<ButtonProps, 'onClick' | 'loading' | 'disabled'>;

type Props = {
  title: string;
  currentName: string;
  primaryButtonProps: CustomButtonProps;
  secondaryButtonProps: CustomButtonProps;
  onApply: (name: string) => void;
  onClose: () => void;
  loading?: boolean;
};

const VIEW_NAME_MAX_LENGTH = 140;

const useViewInputNameModal = ({
  title,
  currentName,
  onApply,
  onClose,
  primaryButtonProps,
  secondaryButtonProps,
  loading = false,
}: Props) => {
  const { t } = useLokaliseTranslation('service_management');

  const form = useForm<{ name: string }>({
    defaultValues: {
      name: currentName,
    },
    mode: 'onChange',
  });

  // Use a ref to store callbacks to avoid re-renders -> caused input blur
  const callbacksRef = useRef({ onApply, onClose });
  callbacksRef.current = { onApply, onClose };

  useEffect(() => {
    if (!currentName) return;
    form.reset({ name: currentName });
  }, [currentName, form.reset]);

  const dialogId = useId();
  const { closeDialog } = useDialogLayer();

  const closeInputNameModal = () => closeDialog(dialogId);

  const { openDialog: openInputNameModal } = useDialogLayerItem(dialogId, {
    title,
    onClose: closeInputNameModal,
    primaryButtonProps: {
      ...primaryButtonProps,
      loading,
      onClick: async () => {
        const isValid = await form.trigger();
        if (!isValid) {
          return;
        }
        callbacksRef.current.onApply(form.getValues('name'));
      },
    },
    secondaryButtonProps: {
      ...secondaryButtonProps,
      disabled: loading,
      onClick: () => {
        callbacksRef.current.onClose();
      },
    },
    body: (
      <FormProvider {...form}>
        <HuFormInputClassic
          name="name"
          rules={{
            required: true,
            maxLength: {
              value: VIEW_NAME_MAX_LENGTH,
              message: t('max_length', { count: VIEW_NAME_MAX_LENGTH }),
            },
          }}
          inputProps={{
            label: t('name'),
            hasCounter: true,
            maxLength: VIEW_NAME_MAX_LENGTH,
          }}
        />
      </FormProvider>
    ),
    dialogProps: { fullWidth: true },
  });

  return {
    openInputNameModal,
    closeInputNameModal,
  };
};

export default useViewInputNameModal;
