"use client";

/**
 * 我的课程列表页（ai14，P3）
 *
 * 数据源：useMyClasses + JoinClassModal 组件
 * 视图：课程卡片网格（班级名 + 年级 + 班主任 + 学生数 + 学年）
 * 功能：
 * - 搜索筛选（按班级名/年级/班主任 客户端过滤）
 * - 邀请码加入班级（复用 JoinClassModal）
 * - 点击卡片进入详情 /courses/[id]
 *
 * 与 /my-classes 的区别：
 * - /my-classes 偏班级管理（含退出班级操作）
 * - /courses 偏学习入口（仅查看 + 加入，引导进入课程详情）
 *
 * 设计依据：纸感设计（card-paper + mark-left + serif 标题）
 */

import { useState, useCallback, useMemo } from "react";
import Link from "next/link";
import { useMyClasses } from "@/lib/graphql/hooks";
import type { ClassInfo } from "@/lib/graphql/types";
import { JoinClassModal } from "@/components/join-class-modal";

export default function CoursesPage(): JSX.Element {
  const { data, fetching, error, reexecute } = useMyClasses();
  const classes = data ?? [];
  const [modalOpen, setModalOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [feedback, setFeedback] = useState<
    { type: "success" | "error"; message: string } | null
  >(null);

  const handleOpenModal = useCallback((): void => {
    setModalOpen(true);
  }, []);

  const handleCloseModal = useCallback((): void => {
    setModalOpen(false);
  }, []);

  const handleJoined = useCallback(
    (_className: string): void => {
      setFeedback({ type: "success", message: "加入班级成功" });
      reexecute();
    },
    [reexecute],
  );

  // 客户端搜索过滤（按班级名 / 年级 / 班主任）
  const filteredClasses = useMemo(() => {
    if (!searchTerm.trim()) return classes;
    const term = searchTerm.trim().toLowerCase();
    return classes.filter(
      (c) =>
        c.name.toLowerCase().includes(term) ||
        c.grade.toLowerCase().includes(term) ||
        c.homeroomTeacher.toLowerCase().includes(term),
    );
  }, [classes, searchTerm]);

  return (
    <div className="px-6 lg:px-10 py-8 lg:py-10 max-w-7xl mx-auto">
      <header className="mb-6">
        <div className="flex items-start justify-between gap-md">
          <div className="min-w-0 flex-1">
            <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>
          </div>
          <button
            type="button"
            onClick={handleOpenModal}
            className="btn-primary flex-shrink-0"
          >
            加入班级
          </button>
        </div>
      </header>

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

      {/* 搜索框 */}
      <div className="mb-6">
        <label htmlFor="course-search" className="sr-only">
          搜索课程
        </label>
        <input
          id="course-search"
          type="search"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          placeholder="搜索班级名、年级或班主任…"
          className="w-full max-w-md px-md py-sm text-sm rounded-sm"
          style={{
            background: "var(--color-paper)",
            color: "var(--color-ink)",
            border: "1px solid var(--color-rule)",
          }}
        />
      </div>

      {feedback && (
        <div
          className="mb-md p-sm rounded text-sm"
          role="alert"
          style={{
            color:
              feedback.type === "success"
                ? "var(--color-success)"
                : "var(--color-danger)",
            background:
              feedback.type === "success"
                ? "hsl(var(--hue-success), var(--sat-success), 95%)"
                : "hsl(var(--hue-danger), var(--sat-danger), 95%)",
          }}
        >
          {feedback.message}
        </div>
      )}

      {fetching ? (
        <LoadingSkeleton />
      ) : error ? (
        <ErrorState
          message={error.message}
          onRetry={() => reexecute()}
        />
      ) : classes.length === 0 ? (
        <EmptyState onJoin={handleOpenModal} />
      ) : filteredClasses.length === 0 ? (
        <p
          className="text-sm py-lg text-center"
          style={{ color: "var(--color-ink-muted)" }}
          role="status"
        >
          未找到匹配 “{searchTerm}” 的班级
        </p>
      ) : (
        <section
          aria-label="课程列表"
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5"
        >
          {filteredClasses.map((cls) => (
            <CourseCard key={cls.id} cls={cls} />
          ))}
        </section>
      )}

      <JoinClassModal
        open={modalOpen}
        onClose={handleCloseModal}
        onJoined={handleJoined}
      />
    </div>
  );
}

/** 课程卡片 */
function CourseCard({ cls }: { cls: ClassInfo }): JSX.Element {
  return (
    <Link
      href={`/courses/${cls.id}`}
      className="card-paper p-6 flex flex-col group transition hover:shadow-card"
      aria-label={`查看课程 ${cls.name} 详情`}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <p
            className="text-xs uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            {cls.grade} · {cls.year} 学年
          </p>
          <h2
            className="mt-2 text-2xl font-serif text-truncate group-hover:underline"
            style={{ color: "var(--color-ink)" }}
          >
            {cls.name}
          </h2>
        </div>
        <span
          className="badge badge-info flex-shrink-0"
          aria-label={`共 ${cls.studentCount} 名学生`}
        >
          {cls.studentCount} 人
        </span>
      </div>

      <div className="rule-thin my-4" />

      <dl className="space-y-2 text-sm">
        <div className="flex items-baseline justify-between">
          <dt
            className="text-xs uppercase tracking-wider"
            style={{ color: "var(--color-ink-muted)" }}
          >
            班主任
          </dt>
          <dd style={{ color: "var(--color-ink)" }}>
            {cls.homeroomTeacher}
          </dd>
        </div>
      </dl>

      <div className="mt-auto pt-4">
        <p
          className="text-xs group-hover:translate-x-1 transition-transform"
          style={{ color: "var(--color-accent)" }}
        >
          查看课程详情 →
        </p>
      </div>
    </Link>
  );
}

function LoadingSkeleton(): JSX.Element {
  return (
    <div
      aria-busy="true"
      aria-live="polite"
      className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5"
    >
      {[0, 1, 2].map((i) => (
        <div key={i} className="card-paper p-6" aria-hidden="true">
          <div
            className="h-3 w-20 rounded-sm animate-pulse"
            style={{ background: "var(--color-rule)" }}
          />
          <div
            className="mt-3 h-7 w-32 rounded-sm animate-pulse"
            style={{ background: "var(--color-rule)" }}
          />
          <div
            className="mt-6 h-px w-full"
            style={{ background: "var(--color-rule)" }}
          />
          <div
            className="mt-4 h-4 w-24 rounded-sm animate-pulse"
            style={{ background: "var(--color-rule)" }}
          />
        </div>
      ))}
      <span className="sr-only">正在加载课程列表...</span>
    </div>
  );
}

function ErrorState({
  message,
  onRetry,
}: {
  message: string;
  onRetry: () => void;
}): JSX.Element {
  return (
    <div
      role="alert"
      className="card-paper p-8 text-center"
      style={{ borderColor: "var(--color-danger)" }}
    >
      <p
        className="text-base font-serif"
        style={{ color: "var(--color-danger)" }}
      >
        课程列表加载失败
      </p>
      <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        {message}
      </p>
      <button
        type="button"
        onClick={onRetry}
        className="mt-4 btn-secondary text-xs"
      >
        重试
      </button>
    </div>
  );
}

function EmptyState({ onJoin }: { onJoin: () => void }): JSX.Element {
  return (
    <div className="card-paper p-8 text-center">
      <p
        className="text-4xl font-serif"
        style={{ color: "var(--color-ink-subtle)" }}
        aria-hidden="true"
      >
        ✦
      </p>
      <p
        className="mt-4 text-base font-serif"
        style={{ color: "var(--color-ink)" }}
      >
        暂未加入任何班级
      </p>
      <p className="mt-2 text-sm" style={{ color: "var(--color-ink-muted)" }}>
        请联系班主任或教务老师为你分配班级，或使用邀请码加入班级。
      </p>
      <button
        type="button"
        onClick={onJoin}
        className="mt-4 btn-primary"
      >
        加入班级
      </button>
    </div>
  );
}
