"use client";

import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { RequireStudentManage } from "@/components/auth/RequirePermission";
import {
  StudentForm,
  emptyStudentForm,
  toStudentPayload,
  validateStudentForm,
  type StudentFormFieldErrors,
  type StudentFormValues,
} from "@/components/students/StudentForm";
import { apiFieldErrors } from "@/components/forms/FormErrorSummary";
import { primarySubmitClass } from "@/components/forms/FormActions";
import { Button } from "@/components/ui/Button";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { ApiError, apiGet, apiPatch } from "@/lib/api";
import type { EducationStage } from "@/lib/types";

interface StudentDetail {
  id: number;
  first_name: string;
  last_name: string;
  national_code: string;
  is_foreign_national?: boolean;
  gender?: string | null;
  birth_date?: string | null;
  birth_place?: string | null;
  avatar_url?: string | null;
  user_id?: number;
  identity_data?: Record<string, string> | null;
  contact_data?: Record<string, string | boolean | null> | null;
  enrollment?: {
    branch_id?: number | null;
    academic_year_id?: number | null;
    study_field_id?: number | null;
    grade_label?: string | null;
  };
}

export default function EditStudentPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [form, setForm] = useState<StudentFormValues>(emptyStudentForm());
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<StudentFormFieldErrors>({});
  const [loading, setLoading] = useState(false);
  const [booting, setBooting] = useState(true);
  const [userId, setUserId] = useState<number | undefined>(undefined);

  useEffect(() => {
    (async () => {
      setBooting(true);
      try {
        const s = await apiGet<StudentDetail>(`/students/${id}`);
        setUserId(s.user_id);
        const branchId = s.enrollment?.branch_id;
        let education_stage_id = "";
        let grade_level_id = "";
        if (branchId) {
          const stages = await apiGet<EducationStage[]>(`/education-stages?branch_id=${branchId}`);
          const gradeName = s.enrollment?.grade_label;
          for (const stage of stages) {
            const grade = stage.grade_levels?.find((g) => g.name === gradeName);
            if (grade) {
              education_stage_id = String(stage.id);
              grade_level_id = String(grade.id);
              break;
            }
          }
        }
        setForm({
          ...emptyStudentForm(),
          branch_id: branchId ? String(branchId) : "",
          education_stage_id,
          grade_level_id,
          study_field_id: s.enrollment?.study_field_id ? String(s.enrollment.study_field_id) : "",
          academic_year_id: s.enrollment?.academic_year_id ? String(s.enrollment.academic_year_id) : "",
          first_name: s.first_name,
          last_name: s.last_name,
          father_name: s.identity_data?.father_name || s.identity_data?.guardian_name || "",
          national_code: s.national_code,
          is_foreign_national: Boolean(s.is_foreign_national),
          birth_date: s.birth_date ?? "",
          birth_place: s.birth_place ?? "",
          gender: s.gender ?? "",
          guardian_mobile: s.contact_data?.guardian_mobile ?? "",
          landline: s.contact_data?.landline ?? "",
          student_mobile: s.contact_data?.student_mobile ?? "",
          student_uses_guardian_mobile: Boolean(s.contact_data?.student_uses_guardian_mobile),
          email: s.contact_data?.email ?? "",
          home_address: s.contact_data?.home_address ?? "",
          notes: s.identity_data?.notes ?? "",
          avatar_path: s.avatar_url ?? "",
        });
      } catch (err) {
        setError(err instanceof ApiError ? err.message : "خطا");
      } finally {
        setBooting(false);
      }
    })();
  }, [id]);

  const submit = async () => {
    const localErrors = validateStudentForm(form, { allowExisting: true });
    if (Object.keys(localErrors).length > 0) {
      setFieldErrors(localErrors);
      setError(null);
      return;
    }
    setError(null);
    setFieldErrors({});
    setLoading(true);
    try {
      const payload = toStudentPayload(form);
      await apiPatch(`/students/${id}`, {
        first_name: payload.first_name,
        last_name: payload.last_name,
        national_code: payload.national_code,
        is_foreign_national: payload.is_foreign_national,
        gender: payload.gender,
        birth_date: payload.birth_date,
        birth_place: payload.birth_place,
        email: payload.email,
        identity_data: payload.identity_data,
        contact_data: payload.contact_data,
      });
      router.push("/students");
    } catch (err) {
      const mapped = apiFieldErrors(err, {
        first_name: "first_name",
        last_name: "last_name",
        national_code: "national_code",
        email: "email",
        "contact_data.guardian_mobile": "guardian_mobile",
        "contact_data.student_mobile": "student_mobile",
      });
      setFieldErrors(mapped.fields as StudentFormFieldErrors);
      setError(mapped.general);
    } finally {
      setLoading(false);
    }
  };

  return (
    <RequireStudentManage>
      <AppShell
        title="ویرایش دانش‌آموز"
        subtitle="به‌روزرسانی اطلاعات"
        breadcrumbLabels={{
          student: [form.first_name, form.last_name].filter(Boolean).join(" ") || undefined,
        }}
      >
        {booting ? (
          <PageContentSkeleton rows={6} />
        ) : (
          <StudentForm
            value={form}
            onChange={setForm}
            mode="edit"
            userId={userId}
            errors={fieldErrors}
            onErrorsChange={setFieldErrors}
            generalError={error}
            actions={
              <>
                <Button loading={loading} onClick={submit} className={primarySubmitClass}>
                  ذخیره
                </Button>
                <Button variant="secondary" onClick={() => router.push("/students")} className="min-w-[8rem]">
                  بازگشت
                </Button>
              </>
            }
          />
        )}
      </AppShell>
    </RequireStudentManage>
  );
}
