"use client";

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

interface Props {
  initialItems: LessonPlanListItem[];
  subjects: { id: string; name: string }[];
}

export function LessonPlanList({ initialItems, subjects }: Props) {
  const t = useTranslations("lessonPreparation");
  const [items, setItems] = useState(initialItems);
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;

  async function handleFilter(params: {
    query?: string;
    subjectId?: string;
    status?: string;
  }) {
    if (service) {
      const res = await service.getLessonPlans(params);
      if (res.success && res.data) setItems(res.data.items);
      return;
    }
    const res = await getLessonPlansAction(params);
    if (res.success && res.data) setItems(res.data.items);
  }

  return (
    <div className="space-y-4">
      <LessonPlanFilters onFilter={handleFilter} subjects={subjects} />
      {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} />
          ))}
        </div>
      )}
    </div>
  );
}
