"use client";

import { useCallback, useState } from "react";
import { useTranslations } from "next-intl";
import { LessonPlanCard } from "./lesson-plan-card";
import { LessonPlanFilters } from "./lesson-plan-filters";
import { useLessonPlanContextSafe } from "../providers/lesson-plan-provider";
import type { LessonPlanListItem } from "../types";

interface Props {
  initialItems: LessonPlanListItem[];
  subjects: { id: string; name: string }[];
  /**
   * 视图模式：决定卡片的跳转链接和可用操作。
   * - teacher（默认）：跳转到编辑页
   * - student / parent：跳转到只读查看页
   * - admin：跳转到管理员查看页
   * - gradeHead：跳转到教研组长查看页
   */
  viewMode?: "teacher" | "student" | "parent" | "admin" | "gradeHead";
}

export function LessonPlanList({ initialItems, subjects, viewMode = "teacher" }: Props) {
  const t = useTranslations("lessonPreparation");
  const [items, setItems] = useState(initialItems);
  const [error, setError] = useState<string | null>(null);
  // P2 修复：增加筛选加载状态，避免用户重复点击
  const [isLoading, setIsLoading] = useState(false);
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;

  // V3 修复：完全通过 service 调用，不直接 import actions
  // 若未在 Provider 内使用，则不执行任何服务端调用（强制要求 Provider 包裹）
  const handleFilter = useCallback(
    async (params: {
      query?: string;
      subjectId?: string;
      status?: string;
    }) => {
      setError(null);
      if (!service) return;
      setIsLoading(true);
      try {
        const res = await service.getLessonPlans(params);
        if (res.success && res.data) {
          setItems(res.data.items);
        } else {
          setError(res.message ?? t("error.loadFailed"));
        }
      } catch (e) {
        console.error("[LessonPlanList] filter failed", e);
        setError(t("error.loadFailed"));
      } finally {
        setIsLoading(false);
      }
    },
    [service, t],
  );

  return (
    <div className="space-y-4">
      <LessonPlanFilters onFilter={handleFilter} subjects={subjects} isLoading={isLoading} />
      {error && (
        <p className="text-error text-sm bg-error-container/10 px-3 py-2 rounded">
          {error}
        </p>
      )}
      {isLoading && items.length === 0 ? (
        <p className="text-on-surface-variant text-center py-12">
          {t("list.loading")}
        </p>
      ) : items.length === 0 ? (
        <p className="text-on-surface-variant text-center py-12">
          {t("list.empty")}
        </p>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {items.map((p) => (
            <LessonPlanCard key={p.id} plan={p} viewMode={viewMode} />
          ))}
        </div>
      )}
    </div>
  );
}
