import { useState, useEffect } from "react";
import ipcTypes from "../../../../../util/ipcTypes.json";
import {
  PaintScaleConfig,
  PaintScaleType,
} from "../../../../../util/types/paintScale";
import { message } from "antd";
import { useTranslation } from "react-i18next";

type ConfigType = "input" | "output";

export const usePaintScaleConfig = (configType: ConfigType) => {
  const [paintScaleConfigs, setPaintScaleConfigs] = useState<
    PaintScaleConfig[]
  >([]);
  const { t } = useTranslation();

  // Get the appropriate IPC methods based on config type
  const getConfigsMethod =
    configType === "input"
      ? ipcTypes.toMain.settings.paintScale.getInputConfigs
      : ipcTypes.toMain.settings.paintScale.getOutputConfigs;

  const setConfigsMethod =
    configType === "input"
      ? ipcTypes.toMain.settings.paintScale.setInputConfigs
      : ipcTypes.toMain.settings.paintScale.setOutputConfigs;

  const setPathMethod =
    configType === "input"
      ? ipcTypes.toMain.settings.paintScale.setInputPath
      : ipcTypes.toMain.settings.paintScale.setOutputPath;

  // Load paint scale configs on mount
  useEffect(() => {
    window.electron.ipcRenderer
      .invoke(getConfigsMethod)
      .then((configs: PaintScaleConfig[]) => {
        // Ensure all configs have a pollingInterval and type (for backward compatibility)
        const defaultPolling = configType === "input" ? 1440 : 60;
        const updatedConfigs = configs.map((config) => ({
          ...config,
          pollingInterval: config.pollingInterval || defaultPolling, // Default to 1440 for input, 60 for output
          type: config.type || PaintScaleType.PPG, // Default type if missing
        }));
        setPaintScaleConfigs(updatedConfigs || []);
      })
      .catch((error) => {
        console.error(
          `Failed to load paint scale ${configType} configs:`,
          error,
        );
      });
  }, [getConfigsMethod]);

  // Save configs to store and notify main process of config changes
  const saveConfigs = (configs: PaintScaleConfig[]) => {
    window.electron.ipcRenderer
      .invoke(setConfigsMethod, configs)
      .then(() => {
        // Notify main process to update cron job
        if (configType === "input") {
          window.electron.ipcRenderer.send(
            ipcTypes.toMain.settings.paintScale.updateInputCron,
            configs,
          );
        } else if (configType === "output") {
          window.electron.ipcRenderer.send(
            ipcTypes.toMain.settings.paintScale.updateOutputCron,
            configs,
          );
        }
      })
      .catch((error) => {
        console.error(
          `Failed to save paint scale ${configType} configs:`,
          error,
        );
      });
  };

  // New helper to check if a path is unique across input and output configs
  const checkPathUnique = async (newPath: string): Promise<boolean> => {
    try {
      const inputConfigs: PaintScaleConfig[] =
        await window.electron.ipcRenderer.invoke(
          ipcTypes.toMain.settings.paintScale.getInputConfigs,
        );
      const outputConfigs: PaintScaleConfig[] =
        await window.electron.ipcRenderer.invoke(
          ipcTypes.toMain.settings.paintScale.getOutputConfigs,
        );
      const allConfigs = [...inputConfigs, ...outputConfigs];
      // Allow updating the current config even if its current value equals newPath.
      return !allConfigs.some((config) => config.path === newPath);
    } catch (error) {
      console.error("Failed to check unique path:", error);
      return false;
    }
  };

  // Handle adding a new paint scale config
  const handleAddConfig = (type: PaintScaleType) => {
    const defaultPolling = configType === "input" ? 1440 : 60;
    const newConfig: PaintScaleConfig = {
      id: Date.now().toString(),
      type,
      pollingInterval: defaultPolling, // Default to 1440 for input, 60 for output
    };
    const updatedConfigs = [...paintScaleConfigs, newConfig];
    setPaintScaleConfigs(updatedConfigs);
    saveConfigs(updatedConfigs);
  };

  // Handle removing a config
  const handleRemoveConfig = (id: string) => {
    const updatedConfigs = paintScaleConfigs.filter(
      (config) => config.id !== id,
    );
    setPaintScaleConfigs(updatedConfigs);
    saveConfigs(updatedConfigs);
  };

  // Handle path selection (modified to check directory uniqueness)
  const handlePathChange = async (id: string) => {
    try {
      const path: string | null = await window.electron.ipcRenderer.invoke(
        setPathMethod,
        id,
      );
      if (path) {
        const isUnique = await checkPathUnique(path);
        if (!isUnique) {
          message.error(t("settings.errors.duplicatePath"));
          return;
        }
        const updatedConfigs = paintScaleConfigs.map((config) =>
          config.id === id ? { ...config, path } : config,
        );
        setPaintScaleConfigs(updatedConfigs);
        saveConfigs(updatedConfigs);
      }
    } catch (error) {
      console.error(`Failed to set paint scale ${configType} path:`, error);
    }
  };

  // Handle polling interval change
  const handlePollingIntervalChange = (id: string, pollingInterval: number) => {
    const updatedConfigs = paintScaleConfigs.map((config) =>
      config.id === id ? { ...config, pollingInterval } : config,
    );
    setPaintScaleConfigs(updatedConfigs);
    saveConfigs(updatedConfigs);
  };

  return {
    paintScaleConfigs,
    handleAddConfig,
    handleRemoveConfig,
    handlePathChange,
    handlePollingIntervalChange,
  };
};
