import { useState, useEffect, useCallback } from "react";
import {
  loadNotifSettings,
  saveNotifSettings,
  type NotifSettings,
} from "@/lib/storage";
import {
  requestPermissions,
  getPermissionStatus,
  scheduleDailyDigest,
  cancelDailyDigest,
} from "@/lib/notifications";

export function useNotificationSettings() {
  const [settings, setSettings] = useState<NotifSettings>({
    dailyEnabled: false,
    dailyHour: 9,
    dailyMinute: 0,
    thresholdEnabled: false,
    thresholdPct: 20,
  });
  const [permissionStatus, setPermissionStatus] = useState("undetermined");
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    Promise.all([loadNotifSettings(), getPermissionStatus()]).then(
      ([stored, status]) => {
        setSettings(stored);
        setPermissionStatus(status);
        setLoaded(true);
      }
    );
  }, []);

  const askPermissions = useCallback(async (): Promise<boolean> => {
    const granted = await requestPermissions();
    setPermissionStatus(granted ? "granted" : "denied");
    return granted;
  }, []);

  const update = useCallback(
    async (patch: Partial<NotifSettings>) => {
      const next = { ...settings, ...patch };
      setSettings(next);
      await saveNotifSettings(next);

      // Keep scheduled notification in sync when toggling or changing time
      const dailyChanged =
        "dailyEnabled" in patch ||
        "dailyHour" in patch ||
        "dailyMinute" in patch;
      if (dailyChanged) {
        if (next.dailyEnabled) {
          await scheduleDailyDigest(next.dailyHour, next.dailyMinute, null, null);
        } else {
          await cancelDailyDigest();
        }
      }
    },
    [settings]
  );

  return { settings, permissionStatus, loaded, askPermissions, update };
}
