import { getSupabaseClient } from "@/lib/supabase";
import FormModal from "./FormModal";
import { auth } from "@clerk/nextjs/server";

export type FormContainerProps = {
  table:
  | "teacher"
  | "student"
  | "parent"
  | "subject"
  | "class"
  | "lesson"
  | "exam"
  | "assignment"
  | "result"
  | "attendance"
  | "event"
  | "announcement"
  | "term"
  | "holiday"
  | "schoolTimetableSlot"
  | "timetableTemplate"
  | "timetableEntry";
  type: "create" | "update" | "delete";
  data?: any;
  id?: number | string;
};

const FormContainer = async ({ table, type, data, id }: FormContainerProps) => {
  let relatedData = {};

  const { userId, sessionClaims } = auth();
  const role = (sessionClaims?.metadata as { role?: string })?.role;
  const schoolId = (sessionClaims?.metadata as { schoolId?: string })?.schoolId;
  const currentUserId = userId;

  if (type !== "delete") {
    const supabase = await getSupabaseClient();
    switch (table) {
      case "subject": {
        const { data: subjectTeachers } = await supabase.from("Teacher").select("id, name, surname");
        relatedData = { teachers: subjectTeachers };
        break;
      }
      case "class": {
        const { data: classGrades } = await supabase.from("Grade").select("id, level");
        const { data: classTeachers } = await supabase.from("Teacher").select("id, name, surname");
        relatedData = { teachers: classTeachers, grades: classGrades };
        break;
      }
      case "teacher": {
        const { data: teacherSubjects } = await supabase.from("Subject").select("id, name");
        relatedData = { subjects: teacherSubjects };
        break;
      }
      case "student": {
        const { data: studentGrades } = await supabase.from("Grade").select("id, level");
        const { data: studentClasses } = await supabase.from("Class").select("*, studentClasses:StudentClass(count)");
        const classesWithCount = studentClasses?.map((c: any) => ({
          ...c,
          _count: { students: Array.isArray(c.studentClasses) ? (c.studentClasses[0]?.count ?? 0) : 0 },
        }));
        relatedData = { classes: classesWithCount ?? [], grades: studentGrades };
        break;
      }
      case "lesson": {
        const { data: lessonSubjects } = await supabase.from("Subject").select("id, name");
        const { data: lessonClasses } = await supabase.from("Class").select("id, name");
        const { data: lessonTeachers } = await supabase.from("Teacher").select("id, name, surname");
        relatedData = { subjects: lessonSubjects, classes: lessonClasses, teachers: lessonTeachers };
        break;
      }
      case "assignment": {
        const { data: assignmentLessons } = await supabase.from("Lesson").select("id, name");
        relatedData = { lessons: assignmentLessons };
        break;
      }
      case "result": {
        const { data: resultStudents } = await supabase.from("Student").select("id, name, surname");
        const { data: resultExams } = await supabase.from("Exam").select("id, title");
        const { data: resultAssignments } = await supabase.from("Assignment").select("id, title");
        relatedData = { students: resultStudents, exams: resultExams, assignments: resultAssignments };
        break;
      }
      case "exam": {
        let query = supabase.from("Lesson").select("id, name");
        if (role === "teacher") {
          query = query.eq("teacherId", currentUserId!);
        }
        const { data: examLessons } = await query;
        relatedData = { lessons: examLessons };
        break;
      }

      case "event": {
        const { data: eventClasses } = await supabase.from("Class").select("id, name");
        relatedData = { classes: eventClasses };
        break;
      }
      case "announcement": {
        const { data: announcementClasses } = await supabase.from("Class").select("id, name");
        relatedData = { classes: announcementClasses };
        break;
      }
      case "timetableTemplate": {
        let teacherIds: string[] | null = null;

        if (schoolId) {
          const { data: mappings, error } = await supabase
            .from("TeacherSchool")
            .select("teacherId")
            .eq("schoolId", schoolId);

          if (!error && mappings) {
            teacherIds = mappings.map((m: any) => m.teacherId as string);
          }
        }

        let query = supabase.from("Teacher").select("id, name, surname");
        if (teacherIds && teacherIds.length > 0) {
          query = query.in("id", teacherIds);
        }

        const { data: templateTeachers } = await query;
        relatedData = { teachers: templateTeachers || [] };
        break;
      }
      case "timetableEntry": {
        let classQuery = supabase.from("Class").select("id, name");
        let subjectQuery = supabase.from("Subject").select("id, name");
        let slotQuery = supabase
          .from("SchoolTimetableSlot")
          .select("id, name, startTime, endTime")
          .order("position", { ascending: true });
        if (schoolId) {
          classQuery = classQuery.eq("schoolId", schoolId);
          subjectQuery = subjectQuery.eq("schoolId", schoolId);
          slotQuery = slotQuery.eq("schoolId", schoolId);
        }
        const [{ data: entryClasses }, { data: entrySubjects }, { data: entrySlots }] = await Promise.all([
          classQuery,
          subjectQuery,
          slotQuery,
        ]);
        relatedData = { classes: entryClasses, subjects: entrySubjects, slots: entrySlots };
        break;
      }
      default:
        break;
    }
  }

  return (
    <div className="">
      <FormModal
        table={table}
        type={type}
        data={data}
        id={id}
        relatedData={relatedData}
      />
    </div>
  );
};

export default FormContainer;
