// useNotificationPreferences：通知偏好（P4 localStorage 降级）
// 依据：02-architecture-design.md §14 通知偏好数据模型、ISSUE-033 裁决
// - P4 阶段：localStorage 为主存储，GraphQL 查询提供初始默认值
// - 更新时：先写 localStorage，再尝试 GraphQL mutation（失败不阻塞）
// - P5+ 阶段：切换到后端为主存储

"use client";

import { useEffect, useState, useCallback } from "react";
import { useQuery, useMutation } from "urql";
import {
  MY_NOTIFICATION_PREFERENCES,
  UPDATE_NOTIFICATION_PREFERENCES,
} from "@/lib/graphql/operations";
import type {
  NotificationPreferences,
  NotificationEventType,
  NotificationChannel,
} from "@/types";
import { getLocalStorage, setLocalStorage } from "@/lib/utils";

const PREFS_KEY = "parent_notification_preferences";

interface MyNotificationPreferencesResponse {
  myNotificationPreferences: NotificationPreferences;
}

interface UpdatePreferencesResponse {
  updateNotificationPreferences: { parentId: string; updatedAt: string };
}

export function useNotificationPreferences(parentId: string) {
  const [localPrefs, setLocalPrefs] = useState<NotificationPreferences | null>(
    null,
  );

  // GraphQL 查询（提供初始默认值）
  const [queryResult] = useQuery<MyNotificationPreferencesResponse>({
    query: MY_NOTIFICATION_PREFERENCES,
  });

  const [, updateMutation] = useMutation<UpdatePreferencesResponse>(
    UPDATE_NOTIFICATION_PREFERENCES,
  );

  // 加载：优先 localStorage，无则用 GraphQL 返回值
  useEffect(() => {
    const stored = getLocalStorage(PREFS_KEY);
    if (stored) {
      try {
        setLocalPrefs(JSON.parse(stored) as NotificationPreferences);
        return;
      } catch {
        // fallthrough
      }
    }
    if (queryResult.data?.myNotificationPreferences) {
      setLocalPrefs(queryResult.data.myNotificationPreferences);
    }
  }, [queryResult.data]);

  // 更新单个偏好（ISSUE-033：先写 localStorage）
  const updatePreference = useCallback(
    (
      childId: string,
      eventType: NotificationEventType,
      channel: NotificationChannel,
      enabled: boolean,
    ) => {
      setLocalPrefs((prev) => {
        if (!prev) return prev;
        const childPrefs = prev.preferences[childId] ?? {};
        const next: NotificationPreferences = {
          ...prev,
          preferences: {
            ...prev.preferences,
            [childId]: {
              ...childPrefs,
              [eventType]: {
                ...childPrefs[eventType],
                [channel]: enabled,
              },
            },
          },
          updatedAt: new Date().toISOString(),
        };
        setLocalStorage(PREFS_KEY, JSON.stringify(next));
        // 异步同步到后端（失败不阻塞）
        updateMutation({
          parentId,
          preferences: next.preferences,
          defaults: next.defaults,
        }).catch(() => {
          // P4 localStorage 降级：后端失败不影响本地
        });
        return next;
      });
    },
    [parentId, updateMutation],
  );

  return {
    preferences: localPrefs,
    loading: !localPrefs && queryResult.fetching,
    error: queryResult.error,
    updatePreference,
  };
}
