import { ChangeEventHandler, KeyboardEventHandler, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Button,
  Col,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownToggle,
  Input,
  Row,
} from "reactstrap";
import { observer } from "mobx-react-lite";
import { useTo } from "taehui-ts/fe-utility";

import { useTaehuiStore } from "src/Stores";

const WantInput = observer(() => {
  const { wantInput, setWantInput, wantVariety, setWantVariety } =
    useTaehuiStore();

  const [isWantVarietyOpened, setWantVarietyOpened] = useState(false);

  const { t } = useTranslation();

  const to = useTo();

  const onWant = () => {
    if (wantInput) {
      to(`/want/${wantVariety}/${encodeURIComponent(wantInput)}`);
    }
  };

  const onInput: ChangeEventHandler<HTMLInputElement> = ({
    target: { value },
  }) => {
    setWantInput(value);
  };

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

  const onCloseWantVariety = () => setWantVarietyOpened(!isWantVarietyOpened);

  const onInputWantVariety = (wantVariety: "essay" | "comment") => () => {
    setWantVariety(wantVariety);
  };

  return (
    <Row className="g-0">
      <Col className="m-1" xs="auto">
        <Dropdown isOpen={isWantVarietyOpened} toggle={onCloseWantVariety}>
          <DropdownToggle caret> {t(wantVariety)}</DropdownToggle>
          <DropdownMenu>
            <DropdownItem onClick={onInputWantVariety("essay")}>
              {t("essay")}
            </DropdownItem>
            <DropdownItem onClick={onInputWantVariety("comment")}>
              {t("comment")}
            </DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </Col>
      <Col className="m-1">
        <Input
          type="search"
          value={wantInput}
          onChange={onInput}
          onKeyDown={onInputLower}
        />
      </Col>
      <Col className="m-1" xs="auto">
        <Button color="success" onClick={onWant}>
          {t("onWant")}
        </Button>
      </Col>
    </Row>
  );
});

export default WantInput;
