import React from "react"
import Popover, { PopoverButton, PopoverContent, usePopover } from "../popover"
import Icon from "../icon"
import EditFilter from "./edit-filter"
import { useFilterType } from "./filter-type-context"
import useKey from "./use-key"
import { IconButton } from "../button"

function Filter({ index, filter, onSave, onRemove }) {
  const popover = usePopover()
  const filterType = useFilterType(filter.type)
  const [key, resetKey] = useKey()

  const View = filterType.View
  const icon = filterType.icon(filter)
  const label = filterType.label(filter)

  const handleSave = filter => {
    onSave(index, filter)
    popover.hide()
    resetKey()
  }

  const handleRemove = () => {
    onRemove(index)
  }

  const handleCancel = () => {
    popover.hide()
    resetKey()
  }

  return (
    <div>
      <Popover label="edit filter" popover={popover} arrow={false}>
        <div className="relative group">
          <PopoverButton
            className="px-4 py-2 w-full bg-white text-gray-900 text-left border border-white shadow-lg focus:outline-blue"
            style={{ minHeight: "70px" }}
            aria-label={`Edit filter ${label}`}
          >
            <div className="flex items-center">
              <div className="w-10 text-blue-500 text-xl">
                {icon && <Icon icon={icon} />}
              </div>
              <div className="text-blue-500 font-semibold">
                <View filter={filter} />
              </div>
            </div>
          </PopoverButton>
          <IconButton
            label="remove filter"
            icon="close"
            is="plain"
            type="button"
            onClick={handleRemove}
            className="absolute right-0 top-0 mr-1 mt-1 focus:outline-blue rounded-sm border border-transparent text-gray-700 opacity-0 group-hover:opacity-100 focus:opacity-100"
          />
        </div>
        <PopoverContent className="z-10" style={{ top: "-69px" }}>
          <EditFilter
            key={key}
            filter={filter}
            onCancel={handleCancel}
            onSave={handleSave}
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}

export default Filter
