import React, { forwardRef, useImperativeHandle, useRef } from "react"
import SelectMenu from "../select-menu"
import { IconButton } from "../button"
import AddFilter from "./add-filter"
import Filter from "./filter"
import useResponsiveValue from "../../hooks/use-responsive-value"

function useFocusHandle(ref) {
  const focusable = useRef()

  useImperativeHandle(ref, () => ({
    focus: () => {
      focusable.current.focus()
    },
  }))

  return focusable
}

// Text between each filter, e.g. --- AND ---, --- OR ---
function Splitter({ type }) {
  return (
    <div className="text-center text-xs text-gray-300 my-1 flex items-center justify-center">
      <span className="block border-t border-gray-300 w-4"></span>
      <div className="mx-2 uppercase">
        {type == "collections/all" ? "and" : "or"}
      </div>
      <span className="block border-t border-gray-300 w-4"></span>
    </div>
  )
}

function TypeSelect({ onChange, value }, ref) {
  return (
    <SelectMenu
      ref={ref}
      name="type"
      aria-label="match any, all, or none of the conditions in this filter group"
      onChange={onChange}
      value={value}
      options={[
        { value: "collections/any", label: "any" },
        { value: "collections/all", label: "all" },
        { value: "collections/none", label: "none" },
      ]}
    />
  )
}
TypeSelect = forwardRef(TypeSelect)

function FilterGroup(
  {
    children,
    filters,
    type,
    onRemove,
    index,
    removable,
    onChangeType,
    onAddFilter,
    onSaveFilter,
    onRemoveFilter,
    size = "",
  },
  ref
) {
  const isTabletScreen = useResponsiveValue([false, true], {
    breakpoints: ["xs"],
  })

  const typeSelect = useFocusHandle(ref)

  const handleTypeChange = (event) => {
    onChangeType(index, event.target.value)
  }

  const handleAddFilter = (filter) => {
    onAddFilter(index, filter)
  }

  const handleSaveFilter = (filterIndex, filter) => {
    onSaveFilter(index, filterIndex, filter)
  }

  const handleRemoveFilter = (filterIndex) => {
    onRemoveFilter(index, filterIndex)
  }

  const gridStyle =
    size === "lg" && isTabletScreen
      ? {
          display: "grid",
          gridTemplateColumns:
            "repeat(auto-fill, [col-start] minmax(200px, 1fr) 2rem [col-end])",
          gridGap: "1rem",
        }
      : {}

  return (
    <div className="border border-gray-300 rounded">
      <div className="border-b border-gray-300 py-2 px-4 text-sm flex">
        <div className="flex-grow">
          Matching{" "}
          <TypeSelect
            value={type}
            ref={typeSelect}
            onChange={handleTypeChange}
          />{" "}
          of the following:
        </div>
        {removable && (
          <IconButton
            className="border border-transparent rounded-sm focus:outline-blue text-gray-700 hover:text-gray-800"
            icon="close"
            is="secondary"
            onClick={() => onRemove(index)}
            label="remove group"
          />
        )}
      </div>
      <div className="p-4 bg-gray-50 relative rounded-b" style={gridStyle}>
        {children}
        {filters.map((filter, index) => (
          <React.Fragment key={index}>
            <Filter
              type={type}
              index={index}
              filter={filter}
              onSave={handleSaveFilter}
              onRemove={handleRemoveFilter}
            />
            <Splitter type={type} />
          </React.Fragment>
        ))}

        <AddFilter onSave={handleAddFilter} />
      </div>
    </div>
  )
}
FilterGroup = forwardRef(FilterGroup)

export default FilterGroup
