import React from "react"
import { parseISO, format } from "date-fns"
import SelectMenu from "../../select-menu"
import DatePickerInput from "../../date-picker-input"

const comparisonOptions = [
  { value: "before", label: "before" },
  { value: "after", label: "after" },
]

function View({ filter }) {
  const comparisonOption = comparisonOptions.find(
    comparisonOption => comparisonOption.value === filter.comparison
  )

  let date
  try {
    date = format(parseISO(filter.date), "MMM d, h:mma")
  } catch (err) {
    date = "Invalid date"
  }

  return (
    <>
      <div className="uppercase text-gray-700 text-xs font-normal">
        Subscribers who
      </div>
      <div className="text-blue-500 font-semibold">subscribed</div>
      <div className="uppercase text-gray-700 text-xs font-normal">
        {`${comparisonOption.label} ${date}`}
      </div>
    </>
  )
}
export default {
  View,
  Edit: ({ filter, setFilter }) => {
    const value = filter.date ? parseISO(filter.date) : null

    const handleChange = event => {
      const { name, value } = event.target
      setFilter({ ...filter, [name]: value })
    }

    const handleDateChange = event => {
      const date = event.target.value
      setFilter({ ...filter, date: date.toJSON() })
    }

    return (
      <>
        <SelectMenu
          className="w-full mt-2"
          name="comparison"
          onChange={handleChange}
          value={filter.comparison}
          options={comparisonOptions}
        />
        <DatePickerInput
          className="w-full mt-2"
          name="value"
          onChange={handleDateChange}
          selected={value}
        />
      </>
    )
  },
  icon: () => "calendar-day",
  label: () => "subscription date",
  defaults: { comparison: "before", action_type: "subscribed" },
}
