import { useQuery, useMutation } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { ModemConfig, WifiConfig } from "../types/types";
import { useEffect } from "react";
import { toast } from "sonner";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";

const getWiFiSettings = async () => {
  const response = await fetch(`${camBase}/api/fetch-config?id=ModemAndWifiManager-wifi`, {
    signal: AbortSignal.timeout(600000),
  });
  if (!response.ok) {
    throw new Error("Cannot fetch Wifi settings");
  }
  return response.json();
};

const updateWifiSettings = async (wifiConfig: WifiConfig) => {
  const response = await fetch(`${camBase}/api/update-config`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(wifiConfig),
  });
  if (!response.ok) {
    throw new Error("Cannot update wifi settings");
  }
  return response.json();
};

const getModemSettings = async () => {
  const response = await fetch(`${camBase}/api/fetch-config?id=ModemAndWifiManager-modem`, {
    signal: AbortSignal.timeout(600000),
  });
  if (!response.ok) {
    throw new Error("Cannot fetch modem settings");
  }
  return response.json();
};

const updateModemSettings = async (modemConfig: ModemConfig) => {
  const response = await fetch(`${camBase}/api/update-config`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(modemConfig),
  });
  if (!response.ok) {
    throw new Error("cannot update modem settings");
  }
  return response.json();
};

export const useWifiAndModem = () => {
  const wifiQuery = useQuery({
    queryKey: ["getWifiSettings"],
    queryFn: getWiFiSettings,
  });

  const wifiMutation = useMutation({
    mutationKey: ["updateWifiSettings"],
    mutationFn: (wifiConfig: WifiConfig) => updateWifiSettings(wifiConfig),
    onError: (error) => {
      toast.error("Failed to update WiFi settings", { id: "wiFiSettings" });
      console.error(error);
    },
    onSuccess: () => {
      toast.success("WiFi settings updated successfully", {
        id: "wiFiSettings",
      });
    },
  });

  const modemQuery = useQuery({
    queryKey: ["getModemSettings"],
    queryFn: getModemSettings,
  });

  const modemMutation = useMutation({
    mutationKey: ["updateModemSettings"],
    mutationFn: (modemConfig: ModemConfig) => updateModemSettings(modemConfig),
    onError: (error) => {
      toast.error("Failed to update Modem settings", { id: "modemSettings" });
      console.error(error);
    },
    onSuccess: () => {
      toast.success("Modem settings updated successfully", {
        id: "modemSettings",
      });
    },
  });

  useEffect(() => {
    if (wifiQuery.isError) toast.error("Cannot get WiFi settings", { id: "wiFiSettings" });
  }, [wifiQuery?.error?.message, wifiQuery.isError]);

  useEffect(() => {
    if (modemQuery.isError) toast.error("Cannot get Modem settings", { id: "modemSettings" });
  }, [modemQuery?.error?.message, modemQuery.isError]);
  return {
    wifiQuery,
    wifiMutation,
    modemQuery,
    modemMutation,
  };
};
