"use client";

import { type ReactNode, useState, useEffect } from "react";
import { useClasses, useClassFilter } from "@/hooks/use-classes";
import {
  PageHeader,
  PaperCard,
  Input,
  LoadingState,
  ErrorState,
  EmptyState,
  Table,
  TableRow,
  TableCell,
  Pagination,
} from "@/components/ui";
import { t } from "@/lib/i18n";

export default function ClassesPage(): ReactNode {
  const { filter, setPage, setSearch } = useClassFilter();
  const { data, loading, error } = useClasses(filter);
  const [searchInput, setSearchInput] = useState("");

  useEffect(() => {
    const timer = setTimeout(() => setSearch(searchInput), 300);
    return () => clearTimeout(timer);
  }, [searchInput, setSearch]);

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader title={t("admin.classes.title")} description="全校班级一览" />

      <PaperCard className="p-4 mb-4">
        <Input
          type="search"
          placeholder={t("admin.common.search")}
          value={searchInput}
          onChange={(e) => setSearchInput(e.target.value)}
          style={{ width: 240 }}
        />
      </PaperCard>

      <PaperCard className="p-4">
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {!loading && !error && data && (
          <>
            {data.items.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <>
                <Table
                  headers={[
                    "班级",
                    "年级",
                    "学校",
                    t("admin.classes.headTeacher"),
                    t("admin.classes.studentCount"),
                    t("admin.common.createdAt"),
                  ]}
                >
                  {data.items.map((cls) => (
                    <TableRow key={cls.id}>
                      <TableCell>{cls.name}</TableCell>
                      <TableCell>{cls.gradeName}</TableCell>
                      <TableCell>{cls.schoolName}</TableCell>
                      <TableCell>{cls.headTeacherName || "—"}</TableCell>
                      <TableCell>{cls.studentCount}</TableCell>
                      <TableCell>
                        {new Date(cls.createdAt).toLocaleDateString("zh-CN")}
                      </TableCell>
                    </TableRow>
                  ))}
                </Table>
                <Pagination
                  page={data.page}
                  pageSize={data.pageSize}
                  total={data.total}
                  hasNext={data.hasNext}
                  onPageChange={setPage}
                />
              </>
            )}
          </>
        )}
      </PaperCard>
    </div>
  );
}
