"use client";

/**
 * Settings 页面 - 个人设置（P3 启用编辑模式）
 *
 * 数据来源（ARB-001 §1.2）：
 * - GraphQL MeQuery（读取当前用户信息）
 * - GraphQL UpdateUserMutation（P3 扩展，MSW mock）更新姓名/邮箱
 * - 编辑按钮切换只读/编辑模式
 * - 乐观更新：本地立即展示新值；失败回滚由错误提示
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useEffect } from "react";
import { useQuery, useMutation } from "urql";
import { Loading } from "@edu/ui-components";
import { MeQuery, UpdateUserMutation } from "@/lib/graphql";

export default function SettingsPage() {
  const [result, reexecuteQuery] = useQuery({ query: MeQuery });
  const [updateResult, updateUser] = useMutation(UpdateUserMutation);

  const [editing, setEditing] = useState(false);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 进入编辑模式时用当前用户数据预填表单
  useEffect(() => {
    if (editing && result.data?.me) {
      setName(result.data.me.name);
      setEmail(result.data.me.email);
      setError(null);
    }
  }, [editing, result.data?.me]);

  const handleStartEdit = () => {
    setEditing(true);
  };

  const handleCancel = () => {
    setEditing(false);
    setError(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!name.trim()) {
      setError("姓名不能为空");
      return;
    }
    if (!email.trim() || !email.includes("@")) {
      setError("邮箱格式不正确");
      return;
    }

    setSubmitting(true);
    // 乐观更新：本地立即显示新值（更新成功后 reexecuteQuery 拉取最新数据）
    const res = await updateUser({
      input: { name: name.trim(), email: email.trim() },
    });
    setSubmitting(false);

    if (res.error) {
      setError(res.error.message);
      return;
    }
    // 成功后重新拉取 me 刷新展示
    reexecuteQuery({ requestPolicy: "network-only" });
    setEditing(false);
  };

  return (
    <div className="px-10 py-10">
      <header className="mb-8 flex items-baseline justify-between">
        <div>
          <h1 className="text-3xl font-serif text-ink">个人设置</h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL MeQuery + UpdateUserMutation · P3 编辑模式
          </p>
        </div>
        {!editing && result.data?.me && (
          <button
            type="button"
            onClick={handleStartEdit}
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
          >
            编辑
          </button>
        )}
      </header>

      <div className="rule-thin mb-8" />

      {result.fetching ? (
        <Loading lines={4} />
      ) : result.error ? (
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
      ) : !result.data?.me ? (
        <p className="text-sm italic text-ink-muted">暂无用户信息</p>
      ) : editing ? (
        <section className="max-w-2xl">
          <div className="mb-6">
            <h2 className="text-xl font-serif text-ink mb-2">编辑个人信息</h2>
            <div className="rule-thin mb-4" />
          </div>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                姓名 <span className="text-danger">*</span>
              </label>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-b-2"
                required
              />
            </div>
            <div>
              <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
                邮箱 <span className="text-danger">*</span>
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm text-ink focus:outline-none focus:border-b-2"
                required
              />
            </div>

            {error && (
              <div className="mark-left py-2 border-l-2 border-danger pl-md">
                <p className="text-sm px-3 text-danger">{error}</p>
              </div>
            )}

            <div className="flex items-center gap-4 pt-2">
              <button
                type="submit"
                disabled={submitting}
                className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
              >
                {submitting ? "保存中..." : "保存"}
              </button>
              <button
                type="button"
                onClick={handleCancel}
                disabled={submitting}
                className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70 disabled:opacity-50"
              >
                取消
              </button>
              {updateResult.data && !error && !submitting && (
                <span className="text-tiny text-success">保存成功</span>
              )}
            </div>
          </form>
        </section>
      ) : (
        <section className="max-w-2xl">
          <div className="mb-6">
            <h2 className="text-xl font-serif text-ink mb-2">基本信息</h2>
            <div className="rule-thin mb-4" />
            <dl className="space-y-4">
              <div className="grid grid-cols-3 gap-4 items-baseline">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  用户 ID
                </dt>
                <dd className="col-span-2 text-sm font-mono text-ink">
                  {result.data.me.id}
                </dd>
              </div>
              <div className="grid grid-cols-3 gap-4 items-baseline">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  姓名
                </dt>
                <dd className="col-span-2 text-sm text-ink">
                  {result.data.me.name}
                </dd>
              </div>
              <div className="grid grid-cols-3 gap-4 items-baseline">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  邮箱
                </dt>
                <dd className="col-span-2 text-sm text-ink">
                  {result.data.me.email}
                </dd>
              </div>
              <div className="grid grid-cols-3 gap-4 items-baseline">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  角色
                </dt>
                <dd className="col-span-2 text-sm text-ink">
                  {result.data.me.roles.join(", ") || "无角色"}
                </dd>
              </div>
              <div className="grid grid-cols-3 gap-4 items-baseline">
                <dt className="text-tiny uppercase tracking-wide text-ink-muted">
                  数据范围
                </dt>
                <dd className="col-span-2 text-sm text-ink">
                  {result.data.me.dataScope}
                </dd>
              </div>
            </dl>
          </div>

          <div className="mt-8 p-4 border border-rule rounded-card bg-subtle">
            <p className="text-sm text-ink-muted">
              P3 已启用编辑功能（UpdateUserMutation）。点击右上角"编辑"按钮修改姓名与邮箱。
            </p>
          </div>
        </section>
      )}
    </div>
  );
}
