"use client";

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

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

  const sorted = useMemo<GradeViewModel[]>(() => {
    if (!data) return [];
    return [...data].sort((a, b) => a.sortOrder - b.sortOrder);
  }, [data]);

  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 && (
          <>
            {sorted.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <Table
                headers={[
                  t("admin.common.grade"),
                  t("admin.common.school"),
                  t("admin.school.director"),
                  t("admin.common.class"),
                  t("admin.dashboard.totalStudents"),
                  t("admin.viewports.sortOrder"),
                ]}
              >
                {sorted.map((grade) => (
                  <TableRow key={grade.id}>
                    <TableCell style={{ fontWeight: 500 }}>
                      {grade.name}
                    </TableCell>
                    <TableCell>{grade.schoolName}</TableCell>
                    <TableCell>{grade.directorName ?? "—"}</TableCell>
                    <TableCell>{grade.classCount}</TableCell>
                    <TableCell>{grade.studentCount}</TableCell>
                    <TableCell>{grade.sortOrder}</TableCell>
                  </TableRow>
                ))}
              </Table>
            )}
          </>
        )}
      </PaperCard>
    </>
  );
}
