import * as _ from 'lodash';
import * as React from 'react';
import { useFela } from 'react-fela';
import {
  useremoveMutation,
  useinstalledExtensionsQuery,
} from '../components/generated-model';
import { ExtensionsList } from '../components/ExtensionsList';

export const Installed = (props: any) => {
  const { css } = useFela();
  const { data: installed, loading, ...installedResult } = useinstalledExtensionsQuery();

  const [removeExtension] = useremoveMutation();

  const onRemove = mutate => id => {
    mutate({ variables: { id } })
      .then(() => installedResult.refetch());
  };

  const list = React.useMemo(() =>
    _.get(installed, 'installed'), [installed]);

  const extensions = React.useMemo(() =>
    _.map(list, 'extension'), [list]);

  return (
    <div className={css(styles.root)}>
      <ExtensionsList
        mode="installed"
        loading={loading}
        extensions={extensions}
        onRemove={onRemove(removeExtension)}
        onSelect={(id) => { console.log('Selected Extension ID ', id)}}
      />
    </div>
  );
};

const styles: any = {
  root: props => ({
    width: '100%',
    height: '100%',
    display: 'flex',
    overflowY: 'auto',
    flexDirection: 'column',
  }),
};
