import { useMutation, useQuery } from "@tanstack/react-query";
import { useEffect } from "react";
import { toast } from "sonner";
import type { InitialValuesForm } from "../types/types";
import { CAM_BASE } from "../utils/config";

const getBackOfficeConfig = async (format: string) => {
  const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher-${format?.toLowerCase()}`);
  if (!response.ok) throw new Error("Cannot get Back Office configuration");
  return response.json();
};

const updateBackOfficeConfig = async (data: InitialValuesForm) => {
  const updateConfigPayload = {
    id: `Dispatcher-${data.format.toLowerCase()}`,
    fields: [
      {
        property: "propBackofficeURL",
        value: data.backOfficeURL,
      },
      {
        property: "propConnectTimeoutSeconds",
        value: data.connectTimeoutSeconds,
      },
      {
        property: "propPassword",
        value: data.password,
      },
      {
        property: "propReadTimeoutSeconds",
        value: data.readTimeoutSeconds,
      },
      {
        property: "propUsername",
        value: data.username,
      },
    ],
  };
  const response = await fetch(`${CAM_BASE}/api/update-config`, {
    method: "POST",
    body: JSON.stringify(updateConfigPayload),
  });
  if (!response.ok) throw new Error("Cannot update Back Office configuration");
  return response.json();
};

export const useCameraBackOfficeOutput = (format: string) => {
  const backOfficeQuery = useQuery({
    queryKey: ["backoffice", format],
    queryFn: () => getBackOfficeConfig(format),
    enabled: !!format,
  });

  useEffect(() => {
    if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
  }, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);

  return {
    backOfficeQuery,
  };
};

export const useUpdateBackOfficeConfig = () => {
  const backOfficeMutation = useMutation({
    mutationKey: ["backOfficeUpdate"],
    mutationFn: updateBackOfficeConfig,
    onError: (error) => toast.error(error.message),
    onSuccess: (data) => {
      if (data) {
        toast.success("Settings successfully updated", { id: "dispatchSettings" });
      }
    },
  });
  return { backOfficeMutation };
};
