import React, { FormEvent } from 'react'
import { Button, Label, Select, TextInput } from 'flowbite-react'

import formTheme from '@/lib/themes/form'
import buttonTheme from '@/lib/themes/button'
import SearchButton from '@/lib/components/buttons/SearchButton'
import { SearchFormProps } from '../types'

interface Props {
  searchForm: SearchFormProps
  handleSearch: (e: FormEvent) => void
  setSearchForm: React.Dispatch<React.SetStateAction<SearchFormProps>>
}

export default function SearchForm(props: Props) {
  function resetSearchParams() {
    props.setSearchForm((searchForm) => ({
      ...searchForm,
      params: {
        title: '',
        published: null,
        page: 1,
        limit: 10,
      },
    }))
  }

  return (
    <form className="mt-10" onSubmit={props.handleSearch}>
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 w-full gap-4 max-w-6xl">
        {/* Title */}
        <div className="w-full">
          <div className="mb-2 block">
            <Label theme={formTheme.label} htmlFor="title">
              Title
            </Label>
          </div>
          <TextInput
            theme={formTheme.textInput}
            id="title"
            type="text"
            className="w-full max-w-96"
            placeholder="Title..."
            value={props.searchForm.params.title}
            onChange={(e) =>
              props.setSearchForm((prev) => ({
                ...prev,
                params: {
                  ...prev.params,
                  title: e.target.value,
                },
              }))
            }
          />
        </div>

        {/* Publish Status */}
        <div className="w-full">
          <div className="block mb-2">
            <Label htmlFor="publish_status" theme={formTheme.label}>
              Publish Status
            </Label>
          </div>

          <Select
            id="publish_status"
            theme={formTheme.select}
            className="w-full max-w-96"
            onChange={(e) => {
              props.setSearchForm({
                ...props.searchForm,
                params: {
                  ...props.searchForm.params,
                  published:
                    e.target.value === ''
                      ? null
                      : e.target.value === 'published',
                },
              })
            }}
          >
            <option value="">All</option>
            <option value="published">Published</option>
            <option value="not_published">Not Published</option>
          </Select>
        </div>
      </div>

      <div className="flex gap-4 mt-5">
        <SearchButton isProcessing={props.searchForm.searching} />

        <Button
          type="button"
          color="alternative"
          onClick={resetSearchParams}
          theme={buttonTheme.button}
        >
          Reset
        </Button>
      </div>
    </form>
  )
}
