import { Alert, Button, Modal } from "antd";
import { useQueryClient } from "@tanstack/react-query";
import { useFilters } from "../../../stores/useFilters";
import { usePointSelection } from "../../../stores/usePointSelection";
import { STATUSES } from "../../../config";
import { useState } from "react";
import { useUpdateStatus } from "../../../hooks/useUpdateStatus";
import { ArrowRightOutlined } from "@ant-design/icons";

export const TakeToWorkButton = () => {
  const { filters } = useFilters();
  const { prediction, categories, region } = filters;
  const { selection } = usePointSelection();
  const queryClient = useQueryClient();

  const [isSuccessModalOpened, setIsSuccessModalOpened] = useState(false);

  const { mutate: updateStatus } = useUpdateStatus({
    onSuccess: () => {
      queryClient.invalidateQueries(["table", 1, filters]);
      setIsSuccessModalOpened(true);
    },
  });

  const takeToWork = () => {
    const params = new URLSearchParams({
      status: STATUSES.approve,
      "prediction_current[]": prediction,
      "categories[]": categories,
      "included[]": [...selection.included],
      "excluded[]": [...selection.excluded],
    });

    if (region) {
      if (region.type === "ao") {
        params.append("ao[]", region.id);
      }

      if (region.type === "rayon") {
        params.append("rayon[]", region.id);
      }
    }

    updateStatus(params);
  };

  return (
    <>
      <Button type="primary" block className={"mt-2"} onClick={takeToWork}>
        <span className="mr-1"> Взять в работу</span>
        <ArrowRightOutlined />
      </Button>
      <Modal
        title={" "}
        centered
        open={isSuccessModalOpened}
        footer={[
          <Button
            key="ok-button"
            type="primary"
            onClick={() => setIsSuccessModalOpened(false)}
          >
            Хорошо
          </Button>,
        ]}
      >
        <Alert
          message="Успешно"
          description="Выбранные точки отправлены на согласование. Посмотреть на них можно во второй
          вкладке"
          type="success"
          showIcon
        />
      </Modal>
    </>
  );
};
