import React, { useState, useEffect } from "react"
import { useFilterTypes, useFilterType } from "./filter-type-context"
import Button from "../button"
import SelectMenu, { separator } from "../select-menu"

const filterTypeToOption = filterType =>
  filterType.type === "separator"
    ? separator
    : { value: filterType.type, label: filterType.label }

function EditFilter({ filter, onSave, onCancel } = {}) {
  const [filterState, setFilterState] = useState(filter)

  const filterTypes = useFilterTypes()

  const filterType = useFilterType(filterState.type)

  const validate = filterType.validate || (() => true)

  const options = filterTypes.map(filterTypeToOption)

  useEffect(() => {
    setFilterState(filter)
  }, [filter])

  const handleSave = () => {
    if (!validate(filterState)) return
    onSave(filterState)
  }

  const handleChangeType = event => {
    const { value } = event.target
    const type = filterTypes.find(filterType => filterType.type === value)
    setFilterState({ type: value, ...type.filter.defaults })
  }

  const Edit = filterType.Edit

  return (
    <div className="w-64">
      <div className="p-4">
        <fieldset>
          <legend className="mb-1 text-sm text-gray-800 font-semibold border-none">
            Add Filter
          </legend>
          <SelectMenu
            aria-label="filter type"
            className="w-full"
            onChange={handleChangeType}
            name="type"
            value={filterState.type}
            options={options}
          ></SelectMenu>

          <Edit filter={filterState} setFilter={setFilterState} />
        </fieldset>
      </div>
      <div className="p-4 border-t border-gray-300 flex">
        <Button
          onClick={onCancel}
          className="focus:outline-none text-sm text-gray-700 border border-transparent"
        >
          Cancel
        </Button>
        <div className="flex-grow" />
        <Button is="primary" onClick={handleSave} disabled={!validate(filterState)}>
          Add Filter
        </Button>
      </div>
    </div>
  )
}

export default EditFilter
