import { useWantStore } from "@/state/Stores";
import { observer } from "mobx-react-lite";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { ChangeEventHandler, KeyboardEventHandler } from "react";
import { Search } from "react-bootstrap-icons";
import Button from "react-bootstrap/Button";
import Dropdown from "react-bootstrap/Dropdown";
import DropdownItem from "react-bootstrap/DropdownItem";
import DropdownMenu from "react-bootstrap/DropdownMenu";
import DropdownToggle from "react-bootstrap/DropdownToggle";
import FormControl from "react-bootstrap/FormControl";
import InputGroup from "react-bootstrap/InputGroup";

export default observer(() => {
  const { input, setInput, wantVariety, setWantVariety } =
    useWantStore();

  const t = useTranslations();

  const { push } = useRouter();

  const onWant = () => {
    if (input) {
      push(`/want/${wantVariety}/${input}`);
    }
  };

  const onWantInput: ChangeEventHandler<HTMLInputElement> = ({
    target: { value },
  }) => {
    setInput(value);
  };

  const onInputLower: KeyboardEventHandler<HTMLInputElement> = ({ key }) => {
    if (key === "Enter") {
      onWant();
    }
  };

  return (
    <InputGroup>
      <Dropdown
        onSelect={(eventKey) => {
          if (eventKey) {
            setWantVariety(eventKey);
          }
        }}
      >
        <DropdownToggle>{t(wantVariety)}</DropdownToggle>
        <DropdownMenu>
          <DropdownItem eventKey="essay">{t("essay")}</DropdownItem>
          <DropdownItem eventKey="comment">{t("comment")}</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <FormControl
        type="search"
        value={input}
        onChange={onWantInput}
        onKeyDown={onInputLower}
      />
      <Button variant="success" onClick={onWant}>
        <Search />
      </Button>
    </InputGroup>
  );
});
