import {
  Box,
  Cell,
  CustomModalLayout,
  FormField,
  Input,
  InputStatus,
  Layout,
  Modal,
  ModalProps,
  Text,
  TextButton,
} 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 CollectionSaveViewModalProps<
  T,
  F extends FiltersMap = FiltersMap,
> extends Partial<ModalProps> {
  state: CollectionViewsState<T, F>;
}

function _CollectionSaveViewModal<T, F extends FiltersMap = FiltersMap>({
  state,
  ...rest
}: CollectionSaveViewModalProps<T, F>) {
  const {
    views: { saveViewModal, collection },
  } = state;
  const { translate: t } = collection;
  const [nameInputValue, setNameInputValue] = useState('');
  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(() => {
    saveViewModal.events.on('open', sendSaveNewViewSelectedBI);

    return () => {
      saveViewModal.events.off('open', sendSaveNewViewSelectedBI);
    };
  }, []);

  const sendSaveNewViewSelectedBI = () => {
    state.sendSaveNewViewSelectedBI();
  };

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

  const primaryButtonOnClick = useCallback(
    async (event?: FormEvent) => {
      event?.preventDefault();
      if (submitted) {
        return;
      }

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

      setSubmitted(true);
      await state.saveNewView(nameInputValue);
      onCloseModal();
    },
    [submitted, nameInputValue],
  );

  return (
    <Modal
      {...rest}
      onAfterClose={() => {
        setSubmitted(false);
      }}
      isOpen={saveViewModal.isOpen}
    >
      <form onSubmit={primaryButtonOnClick}>
        <CustomModalLayout
          overflowY="visible"
          title={t('cairo.table.saveViewModal.title')}
          subtitle={
            <Box>
              <Text secondary>
                {t('cairo.table.saveViewModal.body')}
                {state.learnMoreLink && (
                  <>
                    {' '}
                    <TextButton
                      as="a"
                      rel="noopener"
                      target="_blank"
                      href={state.learnMoreLink}
                      dataHook="save-view-modal-learn-more-link"
                    >
                      {t('cairo.table.saveViewModal.learnMoreLink')}
                    </TextButton>
                  </>
                )}
              </Text>
            </Box>
          }
          primaryButtonText={
            submitted ? undefined : t('cairo.saveViewModal.saveButton')
          }
          primaryButtonProps={{
            children: submitted && (
              <TextWidthLoader
                size="tiny"
                text={t('cairo.saveViewModal.saveButton')}
              />
            ),
          }}
          primaryButtonOnClick={primaryButtonOnClick}
          secondaryButtonText={t('cairo.saveViewModal.cancelButton')}
          secondaryButtonOnClick={onCloseModal}
          onCloseButtonClick={onCloseModal}
          dataHook="save-view-modal"
          width="510px"
        >
          <Layout>
            <Cell>
              <FormField
                label={t('cairo.table.saveViewModal.nameLabel')}
                dataHook="save-view-modal-form-field"
              >
                <Input
                  autoFocus
                  placeholder={
                    state.viewNamePlaceholder ??
                    t('cairo.table.saveViewModal.placeholder')
                  }
                  dataHook="save-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 CollectionSaveViewModal = observer(_CollectionSaveViewModal);
