import { Alert, Button, Modal, Spin } from "antd";
import { useQueryClient } from "@tanstack/react-query";
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";
import { usePendingPointsFilters } from "../../../stores/usePendingPointsFilters";
import { appendFiltersInUse } from "../../../utils.js";

export const TakeToWorkButton = ({ disabled }) => {
  const { filters, ranges } = usePendingPointsFilters();
  const { prediction, categories, region } = filters;
  const { selection } = usePointSelection();
  const queryClient = useQueryClient();
  const [isModalOpened, setIsModalOpened] = useState(false);

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

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

    appendFiltersInUse(params, filters, ranges);

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

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

    updateStatus(params);
  };

  const getModalFooter = () => {
    if (isSuccess) {
      return [
        <Button
          key="ok-button"
          type="primary"
          onClick={() => setIsModalOpened(false)}
        >
          Хорошо
        </Button>,
      ];
    }

    if (isLoading) return null;

    return (
      <div className="flex items-center justify-center gap-x-4">
        <Button onClick={() => setIsModalOpened(false)}>Отмена</Button>
        <Button type="primary" onClick={takeToWork}>
          Да
        </Button>
      </div>
    );
  };

  return (
    <>
      <Button
        type="primary"
        block
        className={"mt-2"}
        onClick={() => setIsModalOpened(true)}
        disabled={disabled}
      >
        <span className="mr-1">Взять в работу</span>
        <ArrowRightOutlined />
      </Button>

      <Modal
        title={" "}
        centered
        open={isModalOpened}
        onCancel={() => setIsModalOpened(false)}
        closable={true}
        footer={getModalFooter()}
      >
        {isSuccess ? (
          <Alert
            message="Успешно"
            description="Выбранные точки отправлены на согласование. Посмотреть на них можно во второй
          вкладке"
            type="success"
            showIcon
          />
        ) : (
          <Title
            text="Уверены, что хотите взять отобранные локации в работу?"
            className="text-center"
          />
        )}

        {isLoading && (
          <div className="flex justify-center py-2">
            <Spin tip="Отправляем на согласование..." size="large" />
          </div>
        )}
      </Modal>
    </>
  );
};
