import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getPoints, useUpdatePostamatId } from "../../../../api";
import { Button, Modal } from "antd";
import { MakeWorkingTable } from "./MakeWorkingTable";
import { useEffect, useState } from "react";
import { usePopup } from "../../../../stores/usePopup";
import { useUpdateStatus } from "../../../../hooks/useUpdateStatus";
import { STATUSES } from "../../../../config";

export const MakeWorkingModal = ({ selectedIds, onClose, onSuccess }) => {
  const { data } = useQuery(["make-working-table", selectedIds], async () => {
    const params = new URLSearchParams({
      page: 1,
      page_size: 100,
      "location_ids[]": selectedIds,
    });

    return await getPoints(params);
  });

  const [hasError, setHasError] = useState(false);

  const [dataSource, setDataSource] = useState([]);

  const [updateError, setUpdateError] = useState(null);

  useEffect(() => {
    setDataSource(data?.results);
  }, [data]);

  const queryClient = useQueryClient();
  const { setPopup } = usePopup();

  const { mutateAsync: updatePostamatId } = useUpdatePostamatId();

  const { mutateAsync: updateStatus } = useUpdateStatus({});

  const handleUpdate = () => {
    const updatePostamatPromises = dataSource.map((it) => {
      const params = new URLSearchParams({
        id: it.id,
        postamat_id: it.postamat_id,
      });

      return updatePostamatId(params);
    });

    const updateStatusParams = new URLSearchParams({
      status: STATUSES.working,
      "location_ids[]": selectedIds,
    });

    const updateStatusPromise = updateStatus(updateStatusParams);

    Promise.all([...updatePostamatPromises, updateStatusPromise])
      .then(() => {
        queryClient.invalidateQueries(["on-approval-points"]);
        setUpdateError(null);
        setPopup(null);
        onSuccess();
        onClose();
      })
      .catch(() =>
        setUpdateError(
          "Введенные идентификаторы уже существуют, попробуйте другие"
        )
      );
  };

  return (
    <Modal
      open={true}
      title="Укажите идентификаторы постаматов"
      onCancel={onClose}
      width={800}
      footer={[
        updateError && (
          <span key="error" className="mr-2 text-primary">
            {updateError}
          </span>
        ),
        <Button
          key="ok-button"
          type="primary"
          onClick={handleUpdate}
          disabled={hasError}
        >
          Обновить статус
        </Button>,
      ]}
    >
      {dataSource && (
        <MakeWorkingTable
          data={dataSource}
          onChange={setDataSource}
          setHasError={setHasError}
        />
      )}
    </Modal>
  );
};
