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

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

import Dialog from '@material-hu/components/design-system/Dialog';
import InputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

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

import { KNOWLEDGE_BASE_NAME_MAX_LENGTH } from '../../constants';
import { useCreateKnowledgeBaseFolder } from '../../hooks/useCreateKnowledgeBaseFolder';

type NewFolderDialogProps = {
  parentPath: string;
  onClose: () => void;
  onSuccess?: (name: string) => void;
};

type FormValues = {
  name: string;
};

const NEW_ROOT_FOLDER_KEYS = 'knowledge_base.new_folder_dialog';
const NEW_SUBFOLDER_KEYS = 'knowledge_base.new_subfolder_dialog';

const NewFolderDialog = ({
  parentPath,
  onClose,
  onSuccess,
}: NewFolderDialogProps) => {
  const { t } = useLokaliseTranslation('agents');

  const isInRoot = parentPath === '';

  const { mutate: createFolder, isLoading } = useCreateKnowledgeBaseFolder();

  const baseKey = isInRoot ? NEW_ROOT_FOLDER_KEYS : NEW_SUBFOLDER_KEYS;

  const form = useForm<FormValues>({
    defaultValues: { name: '' },
  });

  const name = form.watch('name');

  useEffect(() => {
    form.setFocus('name');
  }, [form.setFocus]);

  const handleConfirm = form.handleSubmit(({ name: rawName }) => {
    const trimmed = rawName.trim();
    const newPath = `${parentPath}${trimmed}/`;

    createFolder(
      { path: newPath, isInRoot, name: trimmed },
      {
        onSuccess: () => {
          onSuccess?.(trimmed);
          onClose();
        },
      },
    );
  });

  return (
    <FormProvider {...form}>
      <form onSubmit={handleConfirm}>
        <Dialog
          onClose={onClose}
          title={t(`${baseKey}.title`)}
          primaryButtonProps={{
            children: t('general:create'),
            disabled: !name.trim(),
            loading: isLoading,
            type: 'submit',
          }}
          secondaryButtonProps={{
            children: t('general:cancel'),
            onClick: onClose,
          }}
          body={
            <Stack sx={{ minWidth: 492 }}>
              <InputClassic
                name="name"
                inputProps={{
                  label: t(`${baseKey}.field_label`),
                  placeholder: t(`${baseKey}.placeholder`),
                  maxLength: KNOWLEDGE_BASE_NAME_MAX_LENGTH,
                  hasCounter: true,
                }}
              />
            </Stack>
          }
        />
      </form>
    </FormProvider>
  );
};

export default NewFolderDialog;
