import { Alert, Button, Modal, Popover } 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";
import { Title } from "../../../components/Title";

export const TakeToWorkButton = () => {
  const { filters } = useFilters();
  const { prediction, categories, region } = filters;
  const { selection } = usePointSelection();
  const queryClient = useQueryClient();
  const [popupVisible, setPopupVisible] = useState(false);

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

  const { mutate: updateStatus } = useUpdateStatus({
    onSuccess: () => {
      queryClient.invalidateQueries(["table", 1, filters]);
      setPopupVisible(false);
      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 (
    <>
      <Popover
        trigger="click"
        open={popupVisible}
        onOpenChange={setPopupVisible}
        content={
          <div className="p-2">
            <Title text="Уверены, что хотите взять отобранные локации в работу?" />
            <div className="flex items-center justify-center gap-x-4">
              <Button onClick={() => setPopupVisible(false)}>Отмена</Button>
              <Button type="primary" onClick={takeToWork}>
                Да
              </Button>
            </div>
          </div>
        }
      >
        <Button type="primary" block className={"mt-2"}>
          <span className="mr-1">Взять в работу</span>
          <ArrowRightOutlined />
        </Button>
      </Popover>
      <Modal
        title={" "}
        centered
        open={isSuccessModalOpened}
        footer={[
          <Button
            key="ok-button"
            type="primary"
            onClick={() => setIsSuccessModalOpened(false)}
          >
            Хорошо
          </Button>,
        ]}
      >
        <Alert
          message="Успешно"
          description="Выбранные точки отправлены на согласование. Посмотреть на них можно во второй
          вкладке"
          type="success"
          showIcon
        />
      </Modal>
    </>
  );
};
