import { code } from 'dashboard/generated/controlplane';
import * as _ from 'lodash';
import * as React from 'react';
import { DropDownMenu, DropDownMenuInputItemProps, DropDownMenuInputItemType, Layout, Position, SelectButton, useDialogState } from 'twitch-core-ui';
import { Column, COLUMN_NAMES, displayFunctions, filter } from './util';

import twirp = code.justin.tv.eventbus.controlplane;

interface FilterProps {
  field: Column;
  auditLogs: twirp.AuditLog[];
  addActiveFilter: (f: filter) => void;
  removeActiveFilter: (f: filter) => void;
}

export const Filter = ({ field, auditLogs, addActiveFilter, removeActiveFilter }: FilterProps) => {
  const { dialogProps, anchorProps } = useDialogState();

  const uniqAuditLogs = _.uniqBy(auditLogs, (auditLog) => {
    return displayFunctions[field](auditLog);
  });
  const items: DropDownMenuInputItemProps[] = _.map(uniqAuditLogs, (auditLog) => {
    const displayValue = displayFunctions[field](auditLog);
    return {
      label: displayValue,
      type: DropDownMenuInputItemType.CheckBox,
      name: displayValue,
      onChange: (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.currentTarget.checked === true) {
          addActiveFilter([field, displayValue]);
        } else {
          removeActiveFilter([field, displayValue]);
        }
      },
    };
  });
  return (
    <Layout
      position={Position.Relative}
      padding={{ right: 0.5 }}
    >
      <SelectButton
        {...anchorProps}
      >
        {COLUMN_NAMES[field]}
      </SelectButton>
      <DropDownMenu
        {...dialogProps}
        items={items}
      />
    </Layout>
  );
};
