import { useCallback } from 'react';

import type { FC } from 'react';
import type { CreateLinkFormOnSubmit, EditLinkFormProps } from './EditLinkForm';

import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import { DIALOG_BOX_CONTENT_PADDING_X } from '~/src/components/DialogBox';
import { DialogBoxHeader } from '~/src/components/DialogBox/DialogBoxHeader';
import Text from '~/src/components/Text';
import useHash from '~/src/hooks/useHash';
import { useI18n } from '~/src/lib/i18n';
import { useEditActions } from '../../../ItemPageEdit/useEditActions';
import { EditLinkForm } from './EditLinkForm';

const AddLinkCreateStage: FC<
  {
    onCreate: (params: { dataPath: string }) => void;
    onBack?: false | (() => void);
    onClose?: false | (() => void);
  } & Pick<EditLinkFormProps, 'withPagePeekingSetting'>
> = ({ onCreate, onBack, onClose, ...editLinkFormProps }) => {
  const { t } = useI18n();
  const { addCustomLinkObject: addCustomLink } = useEditActions();
  const { hashParams } = useHash();
  const initialLink = hashParams.link;

  const onSubmit = useCallback<CreateLinkFormOnSubmit>(
    (params) => {
      const dataPath = addCustomLink(params);
      onCreate({ dataPath });
    },
    [addCustomLink]
  );

  return (
    <Box padding={`0 ${DIALOG_BOX_CONTENT_PADDING_X} 2.4rem`}>
      <EditLinkForm
        {...editLinkFormProps}
        autoFocus
        initialLinkValue={initialLink}
        onSubmit={onSubmit}
        renderBefore={() => (
          <DialogBoxHeader
            title={t('itemEdit.itemLinkCreateHeader')}
            isPadded={false}
            onBackClick={onBack || undefined}
            onCloseClick={onClose || undefined}
            withShadow={false}
            renderRight={({ textProps }) => (
              <Clickable isSubmit testId="addButton">
                <Text {...textProps}>{t('app.actions.add')}</Text>
              </Clickable>
            )}
          />
        )}
      />
    </Box>
  );
};

export default AddLinkCreateStage;
