import {
  Cell,
  CustomModalLayout,
  FormField,
  Input,
  InputStatus,
  Layout,
  Modal,
  ModalProps,
} from '@wix/design-system';
import React, { FormEvent, useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { CollectionViewsState } from '../../../../state';
import { TextWidthLoader } from '../../../TextWidthLoader';

export interface CollectionRenameViewModalProps<
  T,
  F extends FiltersMap = FiltersMap,
> extends Partial<ModalProps> {
  state: CollectionViewsState<T, F>;
}

function _CollectionRenameViewModal<T, F extends FiltersMap = FiltersMap>({
  state,
  ...rest
}: CollectionRenameViewModalProps<T, F>) {
  const {
    views: { renameViewModal, collection },
  } = state;
  const { translate: t } = collection;
  const [nameInputValue, setNameInputValue] = useState(
    state.views.currentView?.name ?? '',
  );
  const [statusMessage, setStatusMessage] = useState<string>();
  const [nameInputStatus, setNameInputStatus] = useState<
    InputStatus | undefined
  >(undefined);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (nameInputValue !== '') {
      setNameInputStatus(undefined);
      setStatusMessage(undefined);
    }
  }, [nameInputValue]);

  useEffect(() => {
    renameViewModal.events.on('open', onOpenRenameViewModal);
    return () => {
      renameViewModal.events.off('open', onOpenRenameViewModal);
    };
  }, []);

  const onOpenRenameViewModal = () => {
    setNameInputValue(state.views.currentView?.name ?? '');
    state.sendRenameViewSelectedBI();
  };

  const onCloseModal = () => {
    setNameInputStatus(undefined);
    setNameInputValue('');
    renameViewModal.close();
  };

  const primaryButtonOnClick = useCallback(
    async (event?: FormEvent) => {
      event?.preventDefault();
      if (submitted || nameInputValue === state.views.currentView?.name) {
        return;
      }

      if (nameInputValue === '') {
        setNameInputStatus('error');
        setStatusMessage(t('cairo.noViewName.validationTooltip'));
        return;
      }

      setSubmitted(true);

      await state.renameView(nameInputValue);
      onCloseModal();
    },
    [submitted, nameInputValue],
  );

  return (
    <Modal
      {...rest}
      onAfterClose={() => {
        setSubmitted(false);
      }}
      isOpen={renameViewModal.isOpen}
    >
      <form onSubmit={primaryButtonOnClick}>
        <CustomModalLayout
          overflowY="visible"
          title={t('cairo.manageView.Rename.modal.title')}
          primaryButtonText={
            submitted ? undefined : t('cairo.manageView.Rename.modal.save.CTA')
          }
          primaryButtonProps={{
            children: submitted && (
              <TextWidthLoader
                size="tiny"
                text={t('cairo.manageView.Rename.modal.save.CTA')}
              />
            ),
            disabled: nameInputValue === state.views.currentView?.name,
            type: 'submit',
          }}
          primaryButtonOnClick={primaryButtonOnClick}
          secondaryButtonText={t('cairo.manageView.Rename.modal.cancel.CTA')}
          secondaryButtonOnClick={onCloseModal}
          onCloseButtonClick={onCloseModal}
          dataHook="rename-view-modal"
          width="510px"
        >
          <Layout>
            <Cell>
              <FormField
                label={t('cairo.manageView.Rename.modal.field.title')}
                dataHook="rename-view-modal-form-field"
              >
                <Input
                  autoFocus
                  dataHook="rename-view-modal-input"
                  value={nameInputValue}
                  onChange={(e) => setNameInputValue(e.target.value)}
                  status={nameInputStatus}
                  statusMessage={statusMessage}
                  maxLength={50}
                />
              </FormField>
            </Cell>
          </Layout>
        </CustomModalLayout>
      </form>
    </Modal>
  );
}

export const CollectionRenameViewModal = observer(_CollectionRenameViewModal);
