import { useCallback, useRef } from 'react';

import type { DialogBoxApi } from '~/src/components/DialogBox';
import type { FormApi } from '~/src/components/Form';
import type { SelectedCustomPage } from '~/src/store/types';

import Clickable from '~/src/components/Clickable';
import DialogBox from '~/src/components/DialogBox';
import { DialogBoxHeader } from '~/src/components/DialogBox/DialogBoxHeader';
import Form from '~/src/components/Form';
import InputLabel from '~/src/components/InputLabel';
import { useAppAlert, useAppToast } from '~/src/components/NextApp/lib/CoreUi';
import Sticky from '~/src/components/Sticky';
import Text from '~/src/components/Text';
import TextInput from '~/src/components/TextInput';
import useIsLargeScreen from '~/src/hooks/useIsLargeScreen';
import { useI18n } from '~/src/lib/i18n';
import wait from '~/src/lib/utils/wait';
import { patchCustomPage } from '~/src/store/customPages/actions/patch';
import { useDispatch } from '~/src/store/redux';

interface EditDetailsDialogProps {
  page: SelectedCustomPage;
  onClose: () => void;
}

const EditDetailsDialog = ({ onClose, page }: EditDetailsDialogProps) => {
  const dialogBoxRef = useRef<DialogBoxApi>(null);
  const formApiRef = useRef<FormApi>(null);
  const close = () => dialogBoxRef.current?.close({});
  const isLargeScreen = useIsLargeScreen();
  const appToast = useAppToast();
  const appAlert = useAppAlert();
  const dispatch = useDispatch();
  const { t } = useI18n();

  return (
    <DialogBox
      apiRef={dialogBoxRef}
      onClose={onClose}
      fillViewport={!isLargeScreen}
      testId="editDetailsDialog"
      renderContent={useCallback(
        ({ paddingY, paddingX }) => {
          return (
            <>
              <Sticky>
                <DialogBoxHeader
                  withShadow
                  title={t('item.editCustomPageDetails.dialogTitle')}
                  onCloseClick={close}
                  renderRight={({ textProps }) => (
                    <Clickable
                      testId="saveButton"
                      onClick={() => formApiRef.current?.submit()}
                    >
                      <Text {...textProps}>{t('app.actions.save')}</Text>
                    </Clickable>
                  )}
                />
              </Sticky>
              <div
                style={{
                  padding: `3px ${paddingX} ${paddingY}`,
                  overflow: 'hidden',
                }}
              >
                <Form<{ name: string }>
                  testId="editCustomPageDetailsFrom"
                  apiRef={formApiRef}
                  flexColumn
                  gap={paddingY}
                  onSubmit={async ({ values }) => {
                    // Form has not changed
                    if (values.name === page.name) {
                      close();
                      return;
                    }

                    try {
                      await dispatch(
                        patchCustomPage({
                          customPageId: page.id,
                          changes: { name: values.name },
                        })
                      );

                      await wait(300);
                      close();

                      appToast({
                        text: t('item.events.changesSaved'),
                      });
                    } catch (error) {
                      appAlert({
                        title: t('item.events.updateError'),
                        content: error.message,
                      });
                    }
                  }}
                >
                  <InputLabel
                    value={t('item.editCustomPageDetails.name')}
                    description={t(
                      'item.editCustomPageDetails.nameDescription'
                    )}
                  >
                    <TextInput
                      autoFocus
                      testId="editDetailsNameInput"
                      height="5rem"
                      required
                      maxLength={255}
                      name="name"
                      defaultValue={page.name}
                      placeholder={t(
                        'item.editCustomPageDetails.namePlaceholder'
                      )}
                    />
                  </InputLabel>
                </Form>
              </div>
            </>
          );
        },
        [page]
      )}
    />
  );
};

export default EditDetailsDialog;
