import React from "react"
import Popover, { PopoverButton, PopoverContent, usePopover } from "../popover"
import EditFilter from "./edit-filter"
import useKey from "./use-key"

const initialValue = { type: "all_subscribers" }

function AddFilter({ onSave }) {
  const popover = usePopover()

  const [key, resetKey] = useKey()

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

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

  return (
    <Popover label="add-filter" arrow={false} popover={popover}>
      <PopoverButton is="secondary" className="w-full">
        Add Filter
      </PopoverButton>

      <PopoverContent
        style={{ top: "-72px", bottom: "auto" }}
        className="outline-none z-10"
        aria-label="Welcome"
      >
        <EditFilter
          key={key}
          filter={initialValue}
          onSave={handleSave}
          onCancel={handleCancel}
        />
      </PopoverContent>
    </Popover>
  )
}

export default AddFilter
