import React, { useState } from 'react';

import { TextField } from '@mui/material';

import { ControlledAutoComplete } from '@northern.tech/common-ui/forms/Autocomplete';
import ClickFilter from '@northern.tech/common-ui/forms/ClickFilter';
import Filters from '@northern.tech/common-ui/forms/Filters';
import TimeframePicker from '@northern.tech/common-ui/forms/TimeframePicker';
import { getISOStringBoundaries } from '@northern.tech/utils/helpers';

import { dateFormat } from './store/constants';

const getOptionLabel = option => option.title ?? option.email ?? option;

const renderOption = (props, option) => <li {...props}>{getOptionLabel(option)}</li>;

const isUserOptionEqualToValue = ({ email, id }, value) => id === value || email === value || email === value?.email;

const autoSelectProps = {
  autoSelect: true,
  filterSelectedOptions: true,
  getOptionLabel,
  handleHomeEndKeys: true,
  renderOption
};

export const AuditLogFilter = ({
  users,
  selectionState,
  disabled,
  onFiltersChange,
  detailsReset,
  auditLogsTypes,
  dirtyField,
  setDirtyField,
  detailOptions = []
}) => {
  const { detail = '', endDate = null, user = '', startDate = null, type = '' } = selectionState;
  const [date] = useState(getISOStringBoundaries(new Date()));
  const { end: tonight } = date;

  return (
    <ClickFilter disabled={disabled}>
      <Filters
        initialValues={{ startDate, endDate, user, type, detail }}
        defaultValues={{ startDate: null, endDate: null, user: '', type: '', detail: '' }}
        fieldResetTrigger={detailsReset}
        dirtyField={dirtyField}
        clearDirty={setDirtyField}
        filters={[
          {
            key: 'timeframe',
            title: 'Date range',
            Component: TimeframePicker,
            componentProps: {
              tonight,
              fromLabel: 'Start',
              toLabel: 'End',
              format: dateFormat,
              slotProps: { textField: { InputLabelProps: { shrink: true } } },
              fallbackValue: null
            }
          },
          {
            key: 'type',
            title: 'Filter by changes',
            Component: ControlledAutoComplete,
            componentProps: {
              ...autoSelectProps,
              options: auditLogsTypes,
              isOptionEqualToValue: (option, value) => option.value === value.value && option.object_type === value.object_type,
              renderInput: params => <TextField {...params} placeholder="Type" InputProps={{ ...params.InputProps }} />
            }
          },
          {
            key: 'detail',
            title: '',
            Component: ControlledAutoComplete,
            componentProps: {
              ...autoSelectProps,
              freeSolo: true,
              options: detailOptions,
              disabled: !type,
              renderInput: params => <TextField {...params} placeholder="Value" InputProps={{ ...params.InputProps }} />
            }
          },
          {
            key: 'user',
            title: 'Performed by',
            Component: ControlledAutoComplete,
            componentProps: {
              ...autoSelectProps,
              freeSolo: true,
              isOptionEqualToValue: isUserOptionEqualToValue,
              options: Object.values(users),
              renderInput: params => <TextField {...params} placeholder="Select a user" InputProps={{ ...params.InputProps }} />
            }
          }
        ]}
        onChange={onFiltersChange}
      />
    </ClickFilter>
  );
};

export default AuditLogFilter;
