"use client";

/**
 * Attendance 列表页 - 考勤记录
 *
 * 数据来源（P7 扩展，MSW mock）：
 * - GraphQL AttendanceListQuery：按 classId/日期范围/状态筛选 + 分页
 * - GraphQL ClassesQuery：班级下拉选项
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState, useMemo } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";
import {
  AttendanceListQuery,
} from "@/lib/graphql-p7-admin";
import type {
  AttendanceStatus,
  AttendanceRecord,
  AttendanceListFilter,
} from "@/lib/graphql-p7-admin";

const ALL_STATUSES: { value: AttendanceStatus; label: string }[] = [
  { value: "PRESENT", label: "出勤" },
  { value: "LATE", label: "迟到" },
  { value: "EARLY_LEAVE", label: "早退" },
  { value: "LEAVE", label: "请假" },
  { value: "ABSENT", label: "缺勤" },
];

const STATUS_LABEL: Record<AttendanceStatus, string> = {
  PRESENT: "出勤",
  LATE: "迟到",
  EARLY_LEAVE: "早退",
  LEAVE: "请假",
  ABSENT: "缺勤",
};

function statusColor(status: AttendanceStatus): string {
  switch (status) {
    case "PRESENT":
      return "var(--color-success)";
    case "LATE":
      return "var(--color-warning)";
    case "EARLY_LEAVE":
      return "var(--color-warning)";
    case "LEAVE":
      return "var(--color-accent)";
    case "ABSENT":
      return "var(--color-danger)";
    default:
      return "var(--color-ink-muted)";
  }
}

const PAGE_SIZE = 30;

function todayStr(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function dateMinusDays(days: number): string {
  const d = new Date();
  d.setDate(d.getDate() - days);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

export default function AttendanceListPage(): React.ReactNode {
  const [classId, setClassId] = useState("");
  const [startDate, setStartDate] = useState(dateMinusDays(6));
  const [endDate, setEndDate] = useState(todayStr());
  const [selectedStatuses, setSelectedStatuses] = useState<AttendanceStatus[]>(
    [],
  );
  const [page, setPage] = useState(1);

  const [classesResult] = useQuery({ query: ClassesQuery });
  const classes: Class[] = classesResult.data?.classes ?? [];
  const firstClassId = classes[0]?.id ?? "";

  const filter: AttendanceListFilter = useMemo(
    () => ({
      classId: classId || firstClassId || null,
      startDate: startDate || null,
      endDate: endDate || null,
      statuses: selectedStatuses.length > 0 ? selectedStatuses : null,
      page,
      pageSize: PAGE_SIZE,
    }),
    [classId, firstClassId, startDate, endDate, selectedStatuses, page],
  );

  const [result] = useQuery({
    query: AttendanceListQuery,
    variables: { filter },
  });

  const data = result.data?.attendanceList;
  const items: AttendanceRecord[] = data?.items ?? [];
  const total = data?.total ?? 0;
  const totalPages = data?.totalPages ?? 1;

  const toggleStatus = (s: AttendanceStatus): void => {
    setSelectedStatuses((prev) =>
      prev.includes(s) ? prev.filter((x) => x !== s) : [...prev, s],
    );
    setPage(1);
  };

  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 AttendanceListQuery · 班级/日期/状态筛选 + 分页（P7 扩展，MSW mock）
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Link
            href="/attendance/sheet"
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover"
          >
            录入考勤
          </Link>
          <Link
            href="/attendance/stats"
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            统计
          </Link>
          <Link
            href="/attendance/report"
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            报告
          </Link>
        </div>
      </header>

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

      {/* 筛选栏 */}
      <section className="mb-8">
        <div className="grid grid-cols-3 gap-6 mb-4">
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              班级
            </label>
            <select
              value={classId || firstClassId}
              onChange={(e) => {
                setClassId(e.target.value);
                setPage(1);
              }}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            >
              <option value="">请选择班级</option>
              {classes.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              开始日期
            </label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => {
                setStartDate(e.target.value);
                setPage(1);
              }}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            />
          </div>
          <div>
            <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-1">
              结束日期
            </label>
            <input
              type="date"
              value={endDate}
              onChange={(e) => {
                setEndDate(e.target.value);
                setPage(1);
              }}
              className="w-full px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
            />
          </div>
        </div>
        <div>
          <label className="block text-tiny uppercase tracking-wide text-ink-muted mb-2">
            状态（多选）
          </label>
          <div className="flex items-center gap-2 flex-wrap">
            {ALL_STATUSES.map((s) => {
              const active = selectedStatuses.includes(s.value);
              return (
                <button
                  key={s.value}
                  type="button"
                  onClick={() => toggleStatus(s.value)}
                  className={`px-3 py-1 text-tiny uppercase tracking-wide rounded-button border transition-colors ${
                    active
                      ? "bg-accent text-ink-on-accent border-accent"
                      : "bg-transparent text-ink-muted border-rule hover:text-ink"
                  }`}
                >
                  {s.label}
                </button>
              );
            })}
          </div>
        </div>
      </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>
      ) : items.length === 0 ? (
        <Empty title="暂无考勤记录" description="当前筛选条件下没有记录" />
      ) : (
        <>
          {/* 数据表 */}
          <section>
            <div className="flex items-baseline justify-between mb-4">
              <h2 className="text-xl font-serif text-ink">
                考勤明细
                <span className="ml-2 text-sm font-sans text-ink-muted">
                  共 {total} 条
                </span>
              </h2>
              <p className="text-tiny text-ink-muted">
                第 {page} / {totalPages} 页
              </p>
            </div>
            <div className="rule-thin mb-4" />
            <div className="border border-rule rounded-card overflow-hidden">
              <table className="w-full text-sm">
                <thead className="bg-subtle">
                  <tr>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      班级
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      日期
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      学生
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      学号
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      状态
                    </th>
                    <th className="px-4 py-3 text-left text-tiny uppercase tracking-wide text-ink-muted">
                      备注
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {items.map((r) => (
                    <tr key={r.id} className="border-t border-rule">
                      <td className="px-4 py-3 font-serif text-ink">
                        {r.className}
                      </td>
                      <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                        {r.date}
                      </td>
                      <td className="px-4 py-3 font-serif text-ink">
                        {r.studentName}
                      </td>
                      <td className="px-4 py-3 font-mono text-tiny text-ink-muted">
                        {r.studentNo}
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className="inline-block px-2 py-0.5 rounded-button text-tiny font-mono"
                          style={{
                            color: statusColor(r.status),
                            border: `1px solid ${statusColor(r.status)}`,
                          }}
                        >
                          {STATUS_LABEL[r.status]}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-tiny text-ink-muted">
                        {r.note ?? "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* 分页 */}
            <div className="mt-6 flex items-center justify-between">
              <button
                type="button"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page <= 1}
                className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle disabled:opacity-40 disabled:cursor-not-allowed"
              >
                上一页
              </button>
              <span className="text-tiny text-ink-muted">
                第 {page} 页 / 共 {totalPages} 页（每页 {PAGE_SIZE} 条）
              </span>
              <button
                type="button"
                onClick={() =>
                  setPage((p) => Math.min(totalPages, p + 1))
                }
                disabled={page >= totalPages}
                className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle disabled:opacity-40 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </div>
          </section>
        </>
      )}
    </div>
  );
}
