"use client";

import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { BranchSubjectsManager } from "@/components/academic/BranchSubjectsManager";
import { AppShell } from "@/components/app/AppShell";
import { SchoolSetupNav } from "@/components/school/SchoolSetupNav";
import { Alert } from "@/components/ui/Alert";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { ApiError, apiGet } from "@/lib/api";

interface BranchDetail {
  id: number;
  name: string;
}

export default function SchoolSubjectsPage() {
  const { id } = useParams<{ id: string }>();
  const branchId = Number(id);
  const [branch, setBranch] = useState<BranchDetail | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    apiGet<BranchDetail>(`/branches/${branchId}/directory`)
      .then((detail) => {
        setBranch({ id: detail.id, name: detail.name });
        setError(null);
      })
      .catch((err) => setError(err instanceof ApiError ? err.message : "خطا"))
      .finally(() => setLoading(false));
  }, [branchId]);

  return (
    <AppShell
      title="فهرست دروس"
      subtitle={branch ? branch.name : "مشاهده دروس سازمانی و مدیریت دروس اختصاصی"}
      breadcrumbLabels={{ school: branch?.name }}
    >
      <SchoolSetupNav branchId={branchId} current="subjects" />

      {error ? <div className="mb-4"><Alert tone="error">{error}</Alert></div> : null}
      {loading ? (
        <PageContentSkeleton rows={6} />
      ) : (
        <BranchSubjectsManager branchId={branchId} branchName={branch?.name} />
      )}
    </AppShell>
  );
}
