"use client";

/**
 * Settings — 系统设置（ai14，P5，路由 /settings）
 *
 * 数据源：useMyProfile + useUpdateProfile + useChangePassword
 * 视图：
 * - Tab 1：个人资料（姓名、邮箱、手机、性别、简介、偏好学科）
 * - Tab 2：修改密码（当前密码、新密码、确认新密码）
 *
 * 设计依据：纸感设计（card-paper + mark-left 表单区）
 */

import { useState, useCallback, useEffect } from "react";
import {
  useMyProfile,
  useUpdateProfile,
  useChangePassword,
} from "@/lib/graphql/hooks";
import type { StudentProfile, UpdateProfileInput } from "@/lib/graphql/types";
import { cn } from "@/lib/exam-types";

type TabKey = "profile" | "password";

interface ProfileForm {
  name: string;
  email: string;
  phone: string;
  gender: string;
  bio: string;
  preferredSubjectId: string;
}

interface PasswordForm {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const EMPTY_PROFILE_FORM: ProfileForm = {
  name: "",
  email: "",
  phone: "",
  gender: "",
  bio: "",
  preferredSubjectId: "",
};

const EMPTY_PASSWORD_FORM: PasswordForm = {
  currentPassword: "",
  newPassword: "",
  confirmPassword: "",
};

export default function SettingsPage(): JSX.Element {
  const [activeTab, setActiveTab] = useState<TabKey>("profile");
  const { data: profile, fetching, error } = useMyProfile();

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-3xl mx-auto">
      <header className="mb-6">
        <p
          className="text-xs uppercase tracking-wider"
          style={{ color: "var(--color-ink-muted)" }}
        >
          账户
        </p>
        <h1
          className="mt-2 text-3xl lg:text-4xl font-serif"
          style={{ color: "var(--color-ink)" }}
        >
          系统设置
        </h1>
        <p
          className="mt-2 text-sm"
          style={{ color: "var(--color-ink-muted)" }}
        >
          管理个人资料与账户安全。
        </p>
      </header>

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

      {/* Tab 切换 */}
      <div
        className="flex gap-md mb-lg"
        role="tablist"
        aria-label="设置分类"
      >
        <button
          type="button"
          role="tab"
          aria-selected={activeTab === "profile"}
          onClick={() => setActiveTab("profile")}
          className={cn(
            "px-md py-sm text-sm rounded-sm transition-colors",
            activeTab === "profile" ? "font-serif" : "",
          )}
          style={{
            color:
              activeTab === "profile"
                ? "var(--color-accent)"
                : "var(--color-ink-muted)",
            borderBottom:
              activeTab === "profile"
                ? "2px solid var(--color-accent)"
                : "2px solid transparent",
          }}
        >
          个人资料
        </button>
        <button
          type="button"
          role="tab"
          aria-selected={activeTab === "password"}
          onClick={() => setActiveTab("password")}
          className={cn(
            "px-md py-sm text-sm rounded-sm transition-colors",
            activeTab === "password" ? "font-serif" : "",
          )}
          style={{
            color:
              activeTab === "password"
                ? "var(--color-accent)"
                : "var(--color-ink-muted)",
            borderBottom:
              activeTab === "password"
                ? "2px solid var(--color-accent)"
                : "2px solid transparent",
          }}
        >
          修改密码
        </button>
      </div>

      {fetching && !profile ? (
        <p
          className="text-sm"
          style={{ color: "var(--color-ink-muted)" }}
          aria-live="polite"
        >
          加载中…
        </p>
      ) : error ? (
        <div className="mark-left py-md px-md" aria-live="assertive">
          <p
            className="text-sm"
            style={{ color: "var(--color-ink)" }}
          >
            {error.message || "加载失败"}
          </p>
        </div>
      ) : activeTab === "profile" ? (
        <ProfileTab initialProfile={profile} />
      ) : (
        <PasswordTab />
      )}
    </div>
  );
}

/** 个人资料 Tab */
function ProfileTab({
  initialProfile,
}: {
  initialProfile: StudentProfile | null;
}): JSX.Element {
  const [form, setForm] = useState<ProfileForm>(EMPTY_PROFILE_FORM);
  const [feedback, setFeedback] = useState<
    { type: "success" | "error"; message: string } | null
  >(null);
  const { execute, fetching, data, success, errors } = useUpdateProfile();

  // 同步 profile 数据到表单
  useEffect(() => {
    if (initialProfile) {
      setForm({
        name: initialProfile.name,
        email: initialProfile.email,
        phone: initialProfile.phone,
        gender: initialProfile.gender,
        bio: initialProfile.bio,
        preferredSubjectId: initialProfile.preferredSubjectId,
      });
    }
  }, [initialProfile]);

  // 响应 mutation 结果
  useEffect(() => {
    if (!fetching && data !== null) {
      if (success) {
        setFeedback({ type: "success", message: "个人资料已更新" });
      } else if (!success) {
        const errMsg = errors[0]?.message ?? "更新失败";
        setFeedback({ type: "error", message: errMsg });
      }
    }
  }, [data, success, errors, fetching]);

  const handleChange = useCallback(
    (field: keyof ProfileForm, value: string): void => {
      setForm((prev) => ({ ...prev, [field]: value }));
      setFeedback(null);
    },
    [],
  );

  const handleSubmit = useCallback(
    (e: React.FormEvent): void => {
      e.preventDefault();
      const input: UpdateProfileInput = {
        name: form.name,
        email: form.email,
        phone: form.phone,
        gender: form.gender,
        bio: form.bio,
        preferredSubjectId: form.preferredSubjectId,
      };
      execute(input);
    },
    [form, execute],
  );

  return (
    <form onSubmit={handleSubmit} className="space-y-md" aria-label="个人资料表单">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-md">
        <FormField
          label="姓名"
          id="name"
          value={form.name}
          onChange={(v) => handleChange("name", v)}
        />
        <FormField
          label="学号"
          id="studentNo"
          value={initialProfile?.studentNo ?? "—"}
          onChange={() => {}}
          disabled
        />
        <FormField
          label="邮箱"
          id="email"
          type="email"
          value={form.email}
          onChange={(v) => handleChange("email", v)}
        />
        <FormField
          label="手机"
          id="phone"
          value={form.phone}
          onChange={(v) => handleChange("phone", v)}
        />
        <FormField
          label="性别"
          id="gender"
          value={form.gender}
          onChange={(v) => handleChange("gender", v)}
        />
        <FormField
          label="偏好学科 ID"
          id="preferredSubjectId"
          value={form.preferredSubjectId}
          onChange={(v) => handleChange("preferredSubjectId", v)}
        />
      </div>

      <div>
        <label
          htmlFor="bio"
          className="block text-xs mb-xs"
          style={{ color: "var(--color-ink-muted)" }}
        >
          个人简介
        </label>
        <textarea
          id="bio"
          value={form.bio}
          onChange={(e) => handleChange("bio", e.target.value)}
          rows={3}
          className="w-full input-paper"
          aria-label="个人简介"
        />
      </div>

      {feedback && (
        <p
          className="text-sm"
          role="alert"
          style={{
            color:
              feedback.type === "success"
                ? "var(--color-success)"
                : "var(--color-danger)",
          }}
        >
          {feedback.message}
        </p>
      )}

      <div className="flex justify-end">
        <button
          type="submit"
          disabled={fetching}
          className="btn-primary"
        >
          {fetching ? "保存中…" : "保存"}
        </button>
      </div>
    </form>
  );
}

/** 修改密码 Tab */
function PasswordTab(): JSX.Element {
  const [form, setForm] = useState<PasswordForm>(EMPTY_PASSWORD_FORM);
  const [feedback, setFeedback] = useState<
    { type: "success" | "error"; message: string } | null
  >(null);
  const { execute, fetching, data, success, errors } = useChangePassword();

  useEffect(() => {
    if (!fetching && data !== null) {
      if (success) {
        setFeedback({ type: "success", message: "密码已修改" });
        setForm(EMPTY_PASSWORD_FORM);
      } else if (!success) {
        const errMsg = errors[0]?.message ?? "修改失败";
        setFeedback({ type: "error", message: errMsg });
      }
    }
  }, [data, success, errors, fetching]);

  const handleChange = useCallback(
    (field: keyof PasswordForm, value: string): void => {
      setForm((prev) => ({ ...prev, [field]: value }));
      setFeedback(null);
    },
    [],
  );

  const handleSubmit = useCallback(
    (e: React.FormEvent): void => {
      e.preventDefault();
      if (form.newPassword !== form.confirmPassword) {
        setFeedback({ type: "error", message: "两次输入的新密码不一致" });
        return;
      }
      if (form.newPassword.length < 8) {
        setFeedback({ type: "error", message: "新密码至少 8 位" });
        return;
      }
      execute({
        currentPassword: form.currentPassword,
        newPassword: form.newPassword,
      });
    },
    [form, execute],
  );

  return (
    <form
      onSubmit={handleSubmit}
      className="space-y-md max-w-md"
      aria-label="修改密码表单"
    >
      <FormField
        label="当前密码"
        id="currentPassword"
        type="password"
        value={form.currentPassword}
        onChange={(v) => handleChange("currentPassword", v)}
        required
      />
      <FormField
        label="新密码"
        id="newPassword"
        type="password"
        value={form.newPassword}
        onChange={(v) => handleChange("newPassword", v)}
        required
      />
      <FormField
        label="确认新密码"
        id="confirmPassword"
        type="password"
        value={form.confirmPassword}
        onChange={(v) => handleChange("confirmPassword", v)}
        required
      />

      {feedback && (
        <p
          className="text-sm"
          role="alert"
          style={{
            color:
              feedback.type === "success"
                ? "var(--color-success)"
                : "var(--color-danger)",
          }}
        >
          {feedback.message}
        </p>
      )}

      <div className="flex justify-end">
        <button
          type="submit"
          disabled={fetching}
          className="btn-primary"
        >
          {fetching ? "修改中…" : "修改密码"}
        </button>
      </div>
    </form>
  );
}

/** 表单字段组件 */
function FormField({
  label,
  id,
  value,
  onChange,
  type = "text",
  disabled = false,
  required = false,
}: {
  label: string;
  id: string;
  value: string;
  onChange: (value: string) => void;
  type?: string;
  disabled?: boolean;
  required?: boolean;
}): JSX.Element {
  return (
    <div>
      <label
        htmlFor={id}
        className="block text-xs mb-xs"
        style={{ color: "var(--color-ink-muted)" }}
      >
        {label}
        {required && (
          <span style={{ color: "var(--color-danger)" }}> *</span>
        )}
      </label>
      <input
        id={id}
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        required={required}
        className="w-full input-paper"
      />
    </div>
  );
}
