import * as _ from 'lodash';
import { Table, Divider } from 'antd';
import * as React from 'react';
import { useFela } from 'react-fela';
import { Query, Mutation } from 'react-apollo';
import {
  usegalleryQuery,
  useinstallMutation,
  useremoveMutation,
  useinstalledExtensionsQuery,
} from '../components/generated-model';
import { ExtensionsList } from '../components/ExtensionsList';
import { installDocument } from '../components/generated-model';
import { ExtensionSearchForm } from '../components/ExtensionSearchForm';

export interface IExtensionsRequest {
  query?: string;
  first?: number;
  local?: boolean;
  remote?: boolean;
  prioritizeExtensionIDs?: string[];
}

export interface IExtensionsComponentProps {
  styles?: any;
  request: IExtensionsRequest;
}

export const Extensions = (props: IExtensionsComponentProps) => {
  const { css } = useFela();
  const [ids, setIds] = React.useState([]);
  const [text, setText] = React.useState('');
  const [names, setNames] = React.useState([]);
  const [pageSize, setPageSize] = React.useState(20);
  const { data: installed, ...installedResult } = useinstalledExtensionsQuery();
  const { data: gallery, loading, error: galleryError, refetch } = usegalleryQuery({
    variables: { query: { ids, text, names, pageSize } },
  });

  const [removeExtension] = useremoveMutation();
  const [installExtension] = useinstallMutation();

  const onInstall = mutate => extension => {
    mutate({ variables: { vsix: extension.assets.download.uri } })
      .then(() => refetch());
  };

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

  const onSearch = searchText => {
    setText(searchText);
  };

  return (
    <div className={css(styles.root)}>
      <ExtensionSearchForm onSearch={onSearch} />
      <Divider style={{ margin: '0 0 10px 0' }} type="horizontal" />
      <ExtensionsList
        loading={loading}
        mode="gallery"
        onRemove={onRemove(removeExtension)}
        onInstall={onInstall(installExtension)}
        installed={_.get(installed, 'installed')}
        extensions={_.get(gallery, 'gallery.firstPage')}
        onSelect={(id) => { console.log('Selected Extension ID ', id)}}
      />
    </div>
  );
};

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