"use client";

import Link from "next/link";
import { useParams } from "@/lib/route-params";
import { useCallback, useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { RequireStudentManage } from "@/components/auth/RequirePermission";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { StudentGuardianForm } from "@/components/students/StudentGuardianForm";
import { ApiError, apiGet } from "@/lib/api";

export default function EditStudentGuardianPage() {
  const { id, linkId } = useParams<{ id: string; linkId: string }>();
  const studentId = Number(id);
  const guardianLinkId = Number(linkId);
  const [studentName, setStudentName] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadStudent = useCallback(async () => {
    if (!studentId) return;
    setLoading(true);
    setError(null);
    try {
      const data = await apiGet<{
        first_name?: string;
        last_name?: string;
        full_name?: string;
      }>(`/students/${studentId}`);
      setStudentName(
        data.full_name ||
          [data.first_name, data.last_name].filter(Boolean).join(" ") ||
          `دانش‌آموز #${studentId}`,
      );
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری دانش‌آموز");
    } finally {
      setLoading(false);
    }
  }, [studentId]);

  useEffect(() => {
    void loadStudent();
  }, [loadStudent]);

  return (
    <RequireStudentManage>
      <AppShell
        title="ویرایش ولی"
        subtitle={studentName || undefined}
        actions={
          <Link href={`/students/${studentId}/guardians`}>
            <Button variant="secondary">بازگشت به اولیا</Button>
          </Link>
        }
      >
        {loading ? <PageContentSkeleton rows={5} /> : null}
        {error ? <Alert tone="error">{error}</Alert> : null}
        {!loading && !error ? (
          <StudentGuardianForm
            studentId={studentId}
            studentName={studentName}
            mode="edit"
            linkId={guardianLinkId}
          />
        ) : null}
      </AppShell>
    </RequireStudentManage>
  );
}
