// PreferenceForm：通知偏好表单
// 依据：02-architecture-design.md §14 通知偏好数据模型、§15.8 PreferenceForm 设计
// - ISSUE-033：P4 localStorage 降级，更新立即写入 localStorage
// - 三维矩阵：子女 × 事件类型 × 渠道
// - 切换子女标签查看不同子女的偏好

"use client";

import { useState } from "react";
import { useNotificationPreferences } from "@/hooks/useNotificationPreferences";
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { getUser } from "@/lib/auth";
import {
  NOTIFICATION_EVENT_TYPES,
  NOTIFICATION_CHANNELS,
} from "@/lib/schemas/notification-preferences";
import type { NotificationEventType, NotificationChannel } from "@/types";
import { cn } from "@/lib/utils";

const EVENT_LABELS: Record<NotificationEventType, string> = {
  grade_recorded: "成绩发布",
  homework_graded: "作业评分",
  homework_assigned: "作业布置",
  exam_published: "考试发布",
  attendance_alert: "考勤提醒",
  school_announcement: "学校公告",
  teacher_message: "老师消息",
  fee_reminder: "缴费提醒",
  event_invitation: "活动邀请",
};

const CHANNEL_LABELS: Record<NotificationChannel, string> = {
  in_app: "应用内",
  push: "推送",
  sms: "短信",
  email: "邮件",
  wechat: "微信",
};

export function PreferenceForm() {
  const user = getUser();
  const parentId = user?.id ?? "parent-001";
  const { preferences, loading, updatePreference } =
    useNotificationPreferences(parentId);
  const { children, currentChildId } = useChildSwitcher();
  const [activeChildId, setActiveChildId] = useState<string>(
    currentChildId ?? "*",
  );

  if (loading || !preferences) {
    return <span className="skeleton h-64 w-full rounded" />;
  }

  // 获取当前激活子女的偏好（"*" 表示全局默认）
  const scope =
    activeChildId === "*"
      ? preferences.defaults
      : (preferences.preferences[activeChildId] ?? preferences.defaults);

  return (
    <div className="space-y-4">
      {/* 子女切换标签 */}
      <div className="flex gap-1 border-b border-rule">
        <button
          type="button"
          onClick={() => setActiveChildId("*")}
          className={cn(
            "border-b-2 px-4 py-2 text-sm",
            activeChildId === "*"
              ? "border-accent font-medium"
              : "border-transparent text-ink-muted",
          )}
        >
          全局默认
        </button>
        {children.map((child) => (
          <button
            key={child.id}
            type="button"
            onClick={() => setActiveChildId(child.id)}
            className={cn(
              "border-b-2 px-4 py-2 text-sm",
              activeChildId === child.id
                ? "border-accent font-medium"
                : "border-transparent text-ink-muted",
            )}
          >
            <span className="font-serif">{child.name}</span>
          </button>
        ))}
      </div>

      {/* 偏好矩阵表格 */}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-rule">
              <th className="py-2 text-left text-xs text-ink-muted">事件</th>
              {NOTIFICATION_CHANNELS.map((ch) => (
                <th
                  key={ch}
                  className="py-2 text-center text-xs text-ink-muted"
                >
                  {CHANNEL_LABELS[ch]}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {NOTIFICATION_EVENT_TYPES.map((eventType) => {
              const pref = scope[eventType] ?? {};
              return (
                <tr
                  key={eventType}
                  className="border-b border-rule last:border-b-0"
                >
                  <td className="py-2 font-medium">
                    {EVENT_LABELS[eventType]}
                  </td>
                  {NOTIFICATION_CHANNELS.map((channel) => {
                    const checked = pref[channel] ?? false;
                    return (
                      <td key={channel} className="py-2 text-center">
                        <input
                          type="checkbox"
                          checked={checked}
                          aria-label={`${EVENT_LABELS[eventType]} - ${CHANNEL_LABELS[channel]}`}
                          onChange={(e) =>
                            updatePreference(
                              activeChildId,
                              eventType,
                              channel,
                              e.target.checked,
                            )
                          }
                          className="h-4 w-4 rounded border-rule accent-accent"
                        />
                      </td>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <p className="text-xs text-ink-muted">
        偏好设置自动保存到本地（P4 localStorage 降级），后端就绪后将自动同步。
      </p>
    </div>
  );
}

export default PreferenceForm;
