"use client";

import { type ReactNode, useState } from "react";
import { useDepartments, useSchools } from "@/hooks/use-school";
import {
  PaperCard,
  Select,
  LoadingState,
  ErrorState,
  EmptyState,
  Table,
  TableRow,
  TableCell,
} from "@/components/ui";
import { t } from "@/lib/i18n";

export default function DepartmentsPage(): ReactNode {
  const [schoolId, setSchoolId] = useState<string>("");
  const { data: schools, loading: schoolsLoading } = useSchools();
  const { data, loading, error } = useDepartments(schoolId || undefined);

  return (
    <>
      <PaperCard className="p-4 mb-4">
        <Select
          value={schoolId}
          onChange={(e) => setSchoolId(e.target.value)}
          disabled={schoolsLoading}
        >
          <option value="">
            {t("admin.common.all")}
            {t("admin.common.school")}
          </option>
          {schools.map((s) => (
            <option key={s.id} value={s.id}>
              {s.name}
            </option>
          ))}
        </Select>
      </PaperCard>

      <PaperCard className="p-4">
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {!loading && !error && (
          <>
            {data.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <Table
                headers={[
                  "部门",
                  t("admin.common.school"),
                  t("admin.school.leader"),
                  t("admin.school.memberCount"),
                  t("admin.school.subject"),
                ]}
              >
                {data.map((dept) => (
                  <TableRow key={dept.id}>
                    <TableCell style={{ fontWeight: 500 }}>
                      {dept.name}
                    </TableCell>
                    <TableCell>{dept.schoolName}</TableCell>
                    <TableCell>{dept.leaderName ?? "—"}</TableCell>
                    <TableCell>{dept.memberCount}</TableCell>
                    <TableCell>{dept.subject ?? "—"}</TableCell>
                  </TableRow>
                ))}
              </Table>
            )}
          </>
        )}
      </PaperCard>
    </>
  );
}
