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";
  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 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("*, students:Student(count)");
        const classesWithCount = studentClasses?.map(c => ({
          ...c,
          _count: { students: Array.isArray(c.students) ? (c.students as any)[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;
      }
      default:
        break;
    }
  }

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

export default FormContainer;
