"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { useDebounce } from "@/shared/hooks/use-debounce";

interface Props {
  onFilter: (params: {
    query?: string;
    subjectId?: string;
    status?: string;
  }) => void;
  subjects: { id: string; name: string }[];
  // P2 修复：加载状态，禁用输入避免重复请求
  isLoading?: boolean;
}

export function LessonPlanFilters({ onFilter, subjects, isLoading = false }: Props) {
  const t = useTranslations("lessonPreparation");
  const [query, setQuery] = useState("");
  const [subjectId, setSubjectId] = useState<string>("");
  const [status, setStatus] = useState<string>("");
  // 修复 P1-6：搜索 debounce 300ms
  const debouncedQuery = useDebounce(query, 300);

  // 使用 ref 存储 onFilter，避免其引用变化触发 useEffect 无限循环
  const onFilterRef = useRef(onFilter);
  useEffect(() => {
    onFilterRef.current = onFilter;
  }, [onFilter]);

  useEffect(() => {
    onFilterRef.current({
      query: debouncedQuery || undefined,
      subjectId: subjectId || undefined,
      status: status || undefined,
    });
  }, [debouncedQuery, subjectId, status]);

  return (
    <div className="flex gap-2 flex-wrap items-center">
      <label htmlFor="lesson-plan-search" className="sr-only">
        {t("filters.searchPlaceholder")}
      </label>
      <input
        id="lesson-plan-search"
        placeholder={t("filters.searchPlaceholder")}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        disabled={isLoading}
        aria-busy={isLoading}
        className="border border-outline-variant rounded-lg px-3 py-1.5 text-sm disabled:opacity-50"
      />
      <label htmlFor="lesson-plan-subject" className="sr-only">
        {t("filters.allSubjects")}
      </label>
      <select
        id="lesson-plan-subject"
        value={subjectId}
        onChange={(e) => setSubjectId(e.target.value)}
        disabled={isLoading}
        aria-busy={isLoading}
        className="border border-outline-variant rounded-lg px-3 py-1.5 text-sm disabled:opacity-50"
      >
        <option value="">{t("filters.allSubjects")}</option>
        {subjects.map((s) => (
          <option key={s.id} value={s.id}>
            {s.name}
          </option>
        ))}
      </select>
      <label htmlFor="lesson-plan-status" className="sr-only">
        {t("filters.allStatus")}
      </label>
      <select
        id="lesson-plan-status"
        value={status}
        onChange={(e) => setStatus(e.target.value)}
        disabled={isLoading}
        aria-busy={isLoading}
        className="border border-outline-variant rounded-lg px-3 py-1.5 text-sm disabled:opacity-50"
      >
        <option value="">{t("filters.allStatus")}</option>
        <option value="draft">{t("status.draft")}</option>
        <option value="published">{t("status.published")}</option>
      </select>
    </div>
  );
}
