import { useQueryClient } from "@tanstack/react-query";
import { Button, InputNumber } from "antd";
import { useEffect, useState } from "react";
import { useUpdatePostamatId } from "../../../api";
import { StatusSelect } from "../../../components/StatusSelect";
import { Title } from "../../../components/Title";
import { STATUSES } from "../../../config";
import { useUpdateStatus } from "../../../hooks/useUpdateStatus";
import { useClickedPointConfig } from "../../../stores/useClickedPointConfig";
import { isNil } from "../../../utils.js";
import { FeatureProperties } from "./FeatureProperties";

export const OnApprovalPointPopup = ({ feature, point }) => {
  const featureId = feature.properties.id;
  const { setClickedPointConfig } = useClickedPointConfig();

  const { status: initialStatus, postamat_id: initialPostamatId } =
    point;
  const [status, setStatus] = useState(initialStatus);
  const [postamatId, setPostamatId] = useState(initialPostamatId);

  useEffect(() => {
    setStatus(initialStatus);
    setPostamatId(initialPostamatId);
  }, [initialStatus, initialPostamatId]);

  const [needToFillPostamatId, setNeedToFillPostamatId] = useState(
    status === STATUSES.working && isNil(postamatId)
  );

  const [error, setError] = useState("");

  useEffect(() => setClickedPointConfig(featureId), [featureId]);

  const queryClient = useQueryClient();

  const onSuccess = () => {
    queryClient.invalidateQueries(["on-approval-points"]);
    queryClient.invalidateQueries(["clicked-point", featureId]);
  };

  const { mutateAsync: updateStatus, isLoading: isStatusUpdating } =
    useUpdateStatus({});
  const { mutateAsync: updatePostamatId, isLoading: isPostamatIdUpdating } =
    useUpdatePostamatId();

  const isUpdating = isStatusUpdating || isPostamatIdUpdating;

  const makeWorking = async () => {
    const updatePostamatIdParams = new URLSearchParams({
      id: featureId,
      postamat_id: postamatId,
    });

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

    try {
      await updatePostamatId(updatePostamatIdParams);
    } catch (err) {
      setError("Указанный id уже существует, попробуйте другой");
      return;
    }

    await updateStatus(updateStatusParams);

    onSuccess();
    setNeedToFillPostamatId(false);
  };

  const handleStatusChange = (value) => {
    setStatus(value);

    if (value === STATUSES.working) {
      setNeedToFillPostamatId(true);
    } else {
      setNeedToFillPostamatId(false);
      const params = new URLSearchParams({
        status: value,
        "location_ids[]": [featureId],
      });

      updateStatus(params).then(onSuccess);
    }
  };

  const canEdit = true;

  return (
    <>
      <FeatureProperties
        feature={feature}
        point={point}
        dynamicStatus={status}
        postamatId={postamatId}
      />
      {canEdit && (
        <div className="flex justify-center mt-4">
          <div className={"flex flex-col items-center space-y-2"}>
            <Title text="Изменить статус" />
            <StatusSelect isLoading={isUpdating} disabled={isUpdating} value={status} onChange={handleStatusChange} />
            {needToFillPostamatId && (
              <>
                <Title text="Укажите id постамата" />
                <InputNumber
                  className="w-full"
                  min={0}
                  precision={0}
                  value={postamatId}
                  onChange={(value) => setPostamatId(value)}
                />
                {error && (
                  <div className="text-primary text-center">{error}</div>
                )}
                <Button
                  type="primary"
                  disabled={isNil(postamatId)}
                  onClick={makeWorking}
                  loading={isUpdating}
                >
                  Обновить статус
                </Button>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
};
