"use client";

/**
 * 诊断报告列表页（P7-insights）
 *
 * 数据来源：GraphQL DiagnosticReportsQuery
 *
 * 功能：
 * - 类型筛选（individual/class/grade）
 * - 状态筛选（draft/published/archived）
 * - 列表：报告标题/类型/对象/状态/创建时间/操作
 *
 * 维护者：ai13（teacher-portal）
 */

import { useState } from "react";
import { useQuery } from "urql";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import { DiagnosticReportsQuery } from "@/lib/graphql-p7-insights";
import type {
  DiagnosticReportType,
  DiagnosticReportStatus,
  DiagnosticReportItem,
} from "@/lib/graphql-p7-insights";

type TypeFilter = "ALL" | DiagnosticReportType;
type StatusFilter = "ALL" | DiagnosticReportStatus;

const TYPE_OPTIONS: { value: TypeFilter; label: string }[] = [
  { value: "ALL", label: "全部类型" },
  { value: "INDIVIDUAL", label: "个人" },
  { value: "CLASS", label: "班级" },
  { value: "GRADE", label: "年级" },
];

const STATUS_OPTIONS: { value: StatusFilter; label: string }[] = [
  { value: "ALL", label: "全部状态" },
  { value: "DRAFT", label: "草稿" },
  { value: "PUBLISHED", label: "已发布" },
  { value: "ARCHIVED", label: "已归档" },
];

const TYPE_LABEL: Record<DiagnosticReportType, string> = {
  INDIVIDUAL: "个人",
  CLASS: "班级",
  GRADE: "年级",
};

const STATUS_LABEL: Record<DiagnosticReportStatus, string> = {
  DRAFT: "草稿",
  PUBLISHED: "已发布",
  ARCHIVED: "已归档",
};

function formatDate(iso: string): string {
  return iso.slice(0, 16).replace("T", " ");
}

export default function DiagnosticPage(): JSX.Element {
  const [type, setType] = useState<TypeFilter>("ALL");
  const [status, setStatus] = useState<StatusFilter>("ALL");

  const [result] = useQuery({
    query: DiagnosticReportsQuery,
    variables:
      type === "ALL" && status === "ALL"
        ? {}
        : {
            type: type === "ALL" ? null : type,
            status: status === "ALL" ? null : status,
          },
  });

  const reports: DiagnosticReportItem[] = result.data?.diagnosticReports ?? [];

  /** 根据报告类型决定查看链接 */
  function getViewHref(item: DiagnosticReportItem): string {
    if (item.type === "CLASS") {
      // 班级报告 → /diagnostic/class/[classId]（这里用 id 占位，正式版应解析 targetType）
      // 简化：所有班级报告都跳到第一个班级诊断页
      return `/diagnostic/class/550e8400-e29b-41d4-a716-446655440010`;
    }
    if (item.type === "INDIVIDUAL") {
      return `/analytics/stu-001`;
    }
    return `/analytics`;
  }

  return (
    <div className="px-10 py-10">
      <header className="mb-8">
        <h1 className="text-3xl font-serif text-ink">诊断报告</h1>
        <p className="mt-1 text-sm text-ink-muted">
          GraphQL DiagnosticReportsQuery · 诊断报告列表与状态管理（P7-insights）
        </p>
      </header>

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

      {/* 筛选 */}
      <div className="mb-6 flex items-baseline gap-6 flex-wrap">
        <div className="flex items-center gap-3">
          <label className="text-tiny uppercase tracking-wide text-ink-muted">
            类型
          </label>
          <select
            value={type}
            onChange={(e) => setType(e.target.value as TypeFilter)}
            className="px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
          >
            {TYPE_OPTIONS.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
              </option>
            ))}
          </select>
        </div>
        <div className="flex items-center gap-3">
          <label className="text-tiny uppercase tracking-wide text-ink-muted">
            状态
          </label>
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value as StatusFilter)}
            className="px-3 py-2 bg-transparent border-b border-rule text-sm font-sans text-ink focus:outline-none focus:border-accent"
          >
            {STATUS_OPTIONS.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {result.fetching ? (
        <Loading lines={5} />
      ) : 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>
      ) : reports.length === 0 ? (
        <Empty title="暂无诊断报告" description="当前筛选条件下没有报告" />
      ) : (
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left text-tiny uppercase tracking-wide text-ink-muted border-b border-rule">
              <th className="py-3 pr-4 font-normal">报告标题</th>
              <th className="py-3 pr-4 font-normal">类型</th>
              <th className="py-3 pr-4 font-normal">对象</th>
              <th className="py-3 pr-4 font-normal">状态</th>
              <th className="py-3 pr-4 font-normal">创建时间</th>
              <th className="py-3 pr-4 font-normal text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {reports.map((r) => (
              <tr key={r.id} className="border-b border-rule">
                <td className="py-3 pr-4">
                  <Link
                    href={getViewHref(r)}
                    className="font-serif text-ink hover:text-accent"
                  >
                    {r.title}
                  </Link>
                </td>
                <td className="py-3 pr-4 text-ink">{TYPE_LABEL[r.type]}</td>
                <td className="py-3 pr-4 text-ink-muted">{r.targetType}</td>
                <td className="py-3 pr-4">
                  <span className="px-2 py-0.5 rounded bg-subtle text-tiny text-ink">
                    {STATUS_LABEL[r.status]}
                  </span>
                </td>
                <td className="py-3 pr-4 text-ink-muted font-mono text-tiny">
                  {formatDate(r.createdAt)}
                </td>
                <td className="py-3 pr-4 text-right">
                  <Link
                    href={getViewHref(r)}
                    className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
                  >
                    查看
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
}
