import { auth } from "@clerk/nextjs/server";
import { getSupabaseClient } from "@/lib/supabase";
import { linkTeacherToSchool } from "@/lib/actions";

const MySchoolsPage = async () => {
  const { sessionClaims } = auth();
  const role = (sessionClaims?.metadata as { role?: string })?.role;

  if (role !== "teacher") {
    return (
      <div className="bg-white p-4 rounded-md flex-1 m-4 mt-0">
        <h1 className="text-lg font-semibold mb-2">My Schools</h1>
        <p className="text-sm text-gray-500">
          Only teachers can manage school assignments.
        </p>
      </div>
    );
  }

  const supabase = await getSupabaseClient();

  // Current teacher's schools
  const { data: teacherMappings } = await supabase
    .from("TeacherSchool")
    .select("school:School(id, name)")
    .order("schoolId");

  const currentSchools =
    (teacherMappings || [])
      .map((m: any) => m.school)
      .filter((s: any) => !!s) || [];

  const currentSchoolIds = new Set(
    currentSchools.map((s: any) => s.id as string)
  );

  // All available schools to link to (from pre-seeded directory)
  const { data: allSchools } = await supabase
    .from("School")
    .select("id, name")
    .order("name");

  const availableSchools =
    (allSchools || []).filter((s: any) => !currentSchoolIds.has(s.id)) || [];

  return (
    <div className="bg-white p-4 rounded-md flex-1 m-4 mt-0">
      <h1 className="text-lg font-semibold mb-4">My Schools</h1>

      {/* Current schools */}
      <div className="mb-8">
        <h2 className="text-md font-semibold mb-2">Schools you work at</h2>
        {currentSchools.length === 0 ? (
          <p className="text-sm text-gray-500">
            You are not linked to any schools yet. Use the form below to add a
            school you work at.
          </p>
        ) : (
          <ul className="list-disc list-inside text-sm text-gray-700">
            {currentSchools.map((s: any) => (
              <li key={s.id}>{s.name}</li>
            ))}
          </ul>
        )}
      </div>

      {/* Add a new school */}
      <div>
        <h2 className="text-md font-semibold mb-2">Add a school</h2>
        {availableSchools.length === 0 ? (
          <p className="text-sm text-gray-500">
            There are no additional schools available to link.
          </p>
        ) : (
          <form action={linkTeacherToSchool} className="flex flex-col gap-3">
            <select
              name="schoolId"
              required
              className="ring-[1.5px] ring-gray-300 p-2 rounded-md text-sm w-full md:w-1/2"
              defaultValue=""
            >
              <option value="">
                Select a school from the directory
              </option>
              {availableSchools.map((s: any) => (
                <option key={s.id} value={s.id}>
                  {s.name}
                </option>
              ))}
            </select>

            {/* Optional: future place for schedule fields (startDate, endDate, daysOfWeek) */}

            <button
              type="submit"
              className="bg-blue-500 text-white px-3 py-2 text-sm rounded-md w-fit"
            >
              Add School
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

export default MySchoolsPage;

