import React, { useEffect, useState } from 'react'

import { SegmentEventType } from '~/src/types/event'
import { EventsFilter } from '../..'
import { EventIcon } from '../EventIcon'
import { ScreenReaderOnly } from '../styled'

import {
  FiltersBar,
  QueryField,
  Fieldset,
  EventTypeCheckboxLabel,
  HiddenInput,
  EventTypeCheckboxBadge,
  ShowEventTypeFilters,
  ClearEventTypeFilters,
  VDivider
} from './style'


export type EventListFilterProps = {
  filters: EventsFilter
  onFiltersChange: (filters: EventsFilter) => void
}

export const EventListFilter = ({ filters, onFiltersChange }: EventListFilterProps) => {
  const { query, eventTypes } = filters
  const [typeFiltersVisible, setTypeFiltersVisible] = useState<boolean>(eventTypes?.length > 1)
  const eventTypesList: SegmentEventType[] = ['track', 'page', 'identify']

  const handleTypeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const eventType = e.target.value as SegmentEventType

    onFiltersChange({
      ...filters,
      eventTypes: e.target.checked ? [...eventTypes, eventType] : eventTypes.filter((t) => t !== eventType)
    })
  }

  const handleQueryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    onFiltersChange({
      ...filters,
      query: e.target.value
    })
  }

  const handleShowTypesFilterClick = () => setTypeFiltersVisible(true)

  const handleClearTypeFilters = () => {
    onFiltersChange({
      ...filters,
      eventTypes: []
    })
    setTypeFiltersVisible(false)
  }

  useEffect(() => {
    if (eventTypes.length > 0 && !typeFiltersVisible) {
      setTypeFiltersVisible(true)
    }
  }, [eventTypes, typeFiltersVisible])

  return (
    <FiltersBar>
      <QueryField
        aria-label='filter events by query'
        placeholder='Search...'
        value={query || ''}
        onChange={handleQueryChange} />
      <VDivider />
      {typeFiltersVisible ? (
        <Fieldset>
          <ScreenReaderOnly as='legend'>Event types</ScreenReaderOnly>
          {eventTypesList.map((eventType) => (
            <EventTypeCheckboxLabel key={eventType}>
              <ScreenReaderOnly>{eventType} event</ScreenReaderOnly>
              <HiddenInput
                value={eventType}
                checked={eventTypes?.includes(eventType) || false}
                onChange={handleTypeChange} />
              <EventTypeCheckboxBadge aria-hidden>
                <EventIcon size='sm' type={eventType} />
              </EventTypeCheckboxBadge>
            </EventTypeCheckboxLabel>
          ))}
          <ClearEventTypeFilters type='button' onClick={handleClearTypeFilters}>
            Clear
          </ClearEventTypeFilters>
        </Fieldset>
      ) : (
        <ShowEventTypeFilters type='button' onClick={handleShowTypesFilterClick}>
          All events
        </ShowEventTypeFilters>
      )}
    </FiltersBar>
  )
}
