import { useRouter } from "next/router";
import { useCallback } from "react";
import { useExpressionSetQueryId } from "../../hooks";
import { assignExpressionToSet } from "../../model";

// TODO fix promotion algorithm so it uses a destination expression_set_id

export interface DemoteExpressionButtonProps {
  expression_id: number;
}

export function DemoteExpressionButton({
  expression_id,
}: DemoteExpressionButtonProps) {
  const { query, pathname, push } = useRouter();
  const expression_set_id = useExpressionSetQueryId();
  const handleClick = useCallback(() => {
    if (expression_set_id === 1) {
      const filter_ids = query["filter-ids"]
        ? `${query["filter-ids"]} ${expression_id}`
        : `${expression_id}`;
      push({
        pathname,
        query: {
          ...query,
          "filter-ids": filter_ids,
        },
      });
    } else {
      assignExpressionToSet({
        expression_id,
        expression_set_id: Math.max(1, expression_set_id - 1),
      });
    }
  }, [expression_id, expression_set_id, pathname, push, query]);

  return (
    <button
      className="navigation-item bottom text-navigation grow"
      onClick={handleClick}
    >
      <span>Wrong</span>
    </button>
  );
}
