import { Alert, Button, Modal } from "antd";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../../api";
import { useFilters } from "../../stores/useFilters";
import { usePointSelection } from "../../stores/usePointSelection";
import { STATUSES } from "../../config";
import { useUpdateLayerCounter } from "../../stores/useUpdateLayerCounter";
import { useState } from "react";

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

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

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

      return api.put(
        `/api/placement_points/update_status?${params.toString()}`
      );
    },
    onSuccess: () => {
      queryClient.invalidateQueries(["table", 1, filters]);
      toggleUpdateCounter();
      setIsSuccessModalOpened(true);
    },
  });

  const takeToWork = () => {
    mutate();
  };

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