"use client";

/**
 * 选修课列表页
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL ElectiveCoursesQuery：按状态 + 学科筛选选修课列表
 *
 * 布局：
 * - 顶部：标题 + "创建选修课" 按钮
 * - 筛选：状态 select + 学科 select
 * - 列表：课程名/学科/年级/容量/已选数/状态/操作
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ElectiveCoursesQuery } from "@/lib/graphql-p7-advanced";
import type { ElectiveCourseItem } from "@/lib/graphql-p7-advanced";
import { CURRENT_TEACHER_ID } from "@/mocks/fixtures/elective";

/** 状态中文映射 */
const STATUS_LABEL: Record<string, string> = {
  draft: "草稿",
  open: "开放选课",
  closed: "已截止",
  cancelled: "已取消",
};

/** 状态对应的样式令牌（语义色） */
function statusColor(status: string): string {
  switch (status) {
    case "open":
      return "var(--color-success)";
    case "closed":
      return "var(--color-warning)";
    case "cancelled":
      return "var(--color-danger)";
    default:
      return "var(--color-ink-muted)";
  }
}

/** 状态筛选选项 */
const STATUS_OPTIONS: Array<{ value: string; label: string }> = [
  { value: "", label: "全部状态" },
  { value: "draft", label: "草稿" },
  { value: "open", label: "开放选课" },
  { value: "closed", label: "已截止" },
  { value: "cancelled", label: "已取消" },
];

/** 学科筛选选项 */
const SUBJECT_OPTIONS: Array<{ value: string; label: string }> = [
  { value: "", label: "全部学科" },
  { value: "数学", label: "数学" },
  { value: "语文", label: "语文" },
  { value: "英语", label: "英语" },
  { value: "物理", label: "物理" },
  { value: "化学", label: "化学" },
  { value: "生物", label: "生物" },
  { value: "历史", label: "历史" },
  { value: "地理", label: "地理" },
  { value: "信息技术", label: "信息技术" },
  { value: "美术", label: "美术" },
];

export default function ElectiveListPage(): React.ReactNode {
  const [status, setStatus] = useState("");
  const [subject, setSubject] = useState("");

  const [result] = useQuery({
    query: ElectiveCoursesQuery,
    variables: {
      status: status || null,
      subject: subject || null,
    },
  });

  const courses: ElectiveCourseItem[] = result.data?.electiveCourses ?? [];

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <p className="mb-2">
          <Link
            href="/dashboard"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回仪表盘
          </Link>
        </p>
        <h1 className="text-3xl font-serif text-ink">选修课管理</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL ElectiveCoursesQuery · core-edu 域（P7 扩展，MSW mock）
        </p>
      </header>

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

      {/* 操作栏：筛选 + 创建按钮 */}
      <section className="mb-6 flex items-end justify-between gap-4">
        <div className="flex items-end gap-4">
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              状态
            </label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
            >
              {STATUS_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              学科
            </label>
            <select
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              className="px-3 py-2 bg-transparent border border-rule rounded-button text-sm text-ink focus:outline-none"
            >
              {SUBJECT_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
        </div>
        <Link
          href="/elective/create"
          className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
        >
          创建选修课
        </Link>
      </section>

      {result.fetching ? (
        <Loading lines={6} />
      ) : 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>
      ) : courses.length === 0 ? (
        <Empty title="暂无选修课" description="当前筛选条件下没有选修课" />
      ) : (
        <section>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-rule text-left">
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                  课程名
                </th>
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                  学科
                </th>
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                  年级
                </th>
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                  容量
                </th>
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                  已选数
                </th>
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted">
                  状态
                </th>
                <th className="py-3 px-2 text-tiny uppercase tracking-wide text-ink-muted text-right">
                  操作
                </th>
              </tr>
            </thead>
            <tbody>
              {courses.map((course) => {
                const canEdit = course.teacherId === CURRENT_TEACHER_ID;
                return (
                  <tr
                    key={course.id}
                    className="border-b border-rule hover:bg-subtle"
                  >
                    <td className="py-3 px-2">
                      <span className="font-serif text-ink">
                        {course.title}
                      </span>
                      {course.description && (
                        <p className="mt-1 text-tiny text-ink-muted">
                          {course.description}
                        </p>
                      )}
                    </td>
                    <td className="py-3 px-2 text-ink">{course.subject}</td>
                    <td className="py-3 px-2 text-ink">{course.grade}</td>
                    <td className="py-3 px-2 text-ink">{course.capacity}</td>
                    <td className="py-3 px-2 text-ink">
                      {course.enrolledCount}
                      <span className="text-tiny text-ink-muted">
                        /{course.capacity}
                      </span>
                    </td>
                    <td className="py-3 px-2">
                      <span
                        className="text-tiny"
                        style={{ color: statusColor(course.status) }}
                      >
                        {STATUS_LABEL[course.status] ?? course.status}
                      </span>
                    </td>
                    <td className="py-3 px-2 text-right">
                      {canEdit ? (
                        <Link
                          href={`/elective/${course.id}/edit`}
                          className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                        >
                          编辑
                        </Link>
                      ) : (
                        <span className="text-tiny text-ink-muted">
                          非本人课程
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </section>
      )}
    </div>
  );
}
