import React, { useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import {
  Box,
  Search,
  TextButton,
  EmptyState as WSREmptyState,
} from '@wix/design-system';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { TagsBulkAssignPopoverState } from '../../../state/TagsBulkAssignPopoverState';
import { CreateTagButton } from './CreateTagButton';
import { FiltersMap } from '@wix/bex-core';

interface EmptyStateProps<T, F extends FiltersMap> {
  state: TagsBulkAssignPopoverState<T, F>;
}

const _EmptyState = <T, F extends FiltersMap>({
  state,
}: EmptyStateProps<T, F>) => {
  const { translate: t } = useWixPatternsContainer();

  const handleEmptyStateSearchChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      state.handleSearchChange(value);
    },
    [state.handleSearchChange],
  );

  const renderErrorState = useCallback(() => {
    const resolvedError = state.error;
    return (
      <Box height="100%" verticalAlign="middle">
        <WSREmptyState
          dataHook="bulk-assign-tags-error-state"
          theme="page-no-border"
          subtitle={resolvedError?.message}
        >
          {resolvedError?.action?.onClick && (
            <TextButton
              dataHook="bulk-assign-tags-error-state-retry-button"
              onClick={resolvedError?.action?.onClick}
            >
              {resolvedError?.action?.text}
            </TextButton>
          )}
        </WSREmptyState>
      </Box>
    );
  }, [state.error]);

  return (
    <Box direction="vertical" boxSizing="border-box" height="100%">
      {state.isInEmptyState && (
        <Box direction="vertical" padding="SP5 SP5 0">
          <Box>
            <Search
              dataHook="bulk-assign-tags-empty-state-search"
              placeholder={t(
                'cairo.tags.collectionPage.popover.emptyState.search.placeholder',
              )}
              onChange={handleEmptyStateSearchChange}
            ></Search>
          </Box>
          {!!state.searchValue && (
            <Box marginTop="SP4">
              <CreateTagButton state={state} searchValue={state.searchValue} />
            </Box>
          )}
        </Box>
      )}
      {state.isError && renderErrorState()}
      {state.isInEmptyState && !state.searchValue && (
        <WSREmptyState
          dataHook="bulk-assign-tags-empty-state"
          theme="page-no-border"
          subtitle={t('cairo.tags.collectionPage.popover.emptyState.body')}
        />
      )}
    </Box>
  );
};

export const EmptyState = observer(_EmptyState);
