import { useState, useCallback, useEffect } from "react";
import { WallpaperHistoryEntry } from "@/types/wallpaper";
import { STORE_MESSAGES } from "@/ipc/channels/messages";

export function useWallpaperHistory() {
  const [wallpapers, setWallpapers] = useState<WallpaperHistoryEntry[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // Initial fetch of wallpaper history
    const fetchInitialHistory = async () => {
      try {
        const history = await window.electron.ipcRenderer.invoke("store:get:wallpaperHistory");
        setWallpapers((history as WallpaperHistoryEntry[]) || []);
        setError(null);
      } catch (err) {
        console.error("Failed to fetch wallpaper history:", err);
        setError("Failed to load wallpaper history");
        setWallpapers([]);
      }
    };

    fetchInitialHistory();

    // Set up event listener for store updates
    const updateEventChannel = `${STORE_MESSAGES.EVENTS.UPDATED}:${STORE_MESSAGES.KEYS.WALLPAPER_HISTORY}`;

    // Function to handle the update event
    const handleHistoryUpdate = (_event: any, updatedHistory: WallpaperHistoryEntry[]) => {
      try {
        setWallpapers(updatedHistory || []);
        setError(null);
      } catch (err) {
        console.error("Error handling history update:", err);
        setError("Failed to update wallpaper history");
      }
    };

    // Register the event listener
    window.electron.ipcRenderer.on(updateEventChannel, handleHistoryUpdate);

    // Also listen for the generic wallpaper-history-updated event from wallpaperService
    window.electron.ipcRenderer.on(
      "wallpaper-history-updated",
      (_event: any, updatedHistory: WallpaperHistoryEntry[]) => {
        try {
          setWallpapers(updatedHistory || []);
          setError(null);
        } catch (err) {
          console.error("Error handling wallpaper service history update:", err);
          setError("Failed to update wallpaper history");
        }
      },
    );

    // Clean up the event listeners when the component unmounts
    return () => {
      window.electron.ipcRenderer.removeListener(updateEventChannel, handleHistoryUpdate);
      window.electron.ipcRenderer.removeListener("wallpaper-history-updated", handleHistoryUpdate);
    };
  }, []);

  // Add a wallpaper to history (simplified, as main process handles logic)
  const addToHistory = useCallback(async (wallpaper: WallpaperHistoryEntry) => {
    try {
      // Ensure essential fields are present for a history entry
      const entryToAdd: WallpaperHistoryEntry = {
        ...wallpaper,
        setAt: wallpaper.setAt || new Date().toISOString(), // Ensure setAt is present as ISO string
        isUpscaled: wallpaper.isUpscaled || false,
      };

      // Use the existing IPC channel and wrap the entry in an array
      await window.electron.ipcRenderer.invoke(
        `${STORE_MESSAGES.CHANNELS.SET}:${STORE_MESSAGES.OPERATIONS.WALLPAPER_HISTORY}`,
        [entryToAdd], // Pass as array since the handler expects an array
      );

      // The listener for 'store:updated:wallpaperHistory' will update the local state.
      return true;
    } catch (err: any) {
      console.error("Failed to add wallpaper to history via IPC:", err);
      setError(err.message || "Failed to add to history");
      return false;
    }
  }, []);

  const clearWallpaperHistory = useCallback(async () => {
    try {
      await window.electron.ipcRenderer.invoke(
        `${STORE_MESSAGES.CHANNELS.CLEAR}:${STORE_MESSAGES.OPERATIONS.WALLPAPER_HISTORY}`,
      );
      // Listener will update local state to empty.
      setError(null);
    } catch (err: any) {
      console.error("Failed to clear wallpaper history via IPC:", err);
      setError(err.message || "Failed to clear history");
    }
  }, []);

  return {
    wallpapers,
    error,
    addToHistory,
    clearWallpaperHistory,
  };
}
