import React, { useState } from 'react'
import { useCreateSavedSearch } from '../settings/useSavedSearches'

interface SaveSearchFormProps {
  query: string
}

export function SaveSearchForm({ query }: SaveSearchFormProps): React.JSX.Element {
  const [open, setOpen] = useState(false)
  const [name, setName] = useState(query)
  const [saved, setSaved] = useState(false)
  const createMutation = useCreateSavedSearch()

  function handleOpen() {
    setName(query)
    setSaved(false)
    setOpen(true)
  }

  function handleCancel() {
    setOpen(false)
  }

  function handleSave(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim()) return
    createMutation.mutate(
      { name: name.trim(), query },
      {
        onSuccess: () => {
          setSaved(true)
          setTimeout(() => {
            setOpen(false)
            setSaved(false)
          }, 1200)
        },
      },
    )
  }

  if (!open) {
    return (
      <div className="save-search-wrap">
        <button className="save-search-btn" type="button" onClick={handleOpen}>
          save search
        </button>
      </div>
    )
  }

  return (
    <div className="save-search-wrap">
      {saved ? (
        <span className="save-search-check">✓</span>
      ) : (
        <form className="save-search-form-inline" onSubmit={handleSave}>
          <span className="save-search-query-display">{query}</span>
          <input
            className="save-search-name-input"
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="name"
            autoComplete="off"
            autoFocus
          />
          <button
            className="save-search-btn"
            type="submit"
            disabled={createMutation.isPending || !name.trim()}
          >
            {createMutation.isPending ? 'saving…' : 'save'}
          </button>
          <button className="save-search-btn" type="button" onClick={handleCancel}>
            cancel
          </button>
        </form>
      )}
    </div>
  )
}
