import FormContainer from "@/components/FormContainer";
import ListFilterSort from "@/components/ListFilterSort";
import Pagination from "@/components/Pagination";
import Table from "@/components/Table";
import { getSupabaseClient } from "@/lib/supabase";
import { ITEM_PER_PAGE } from "@/lib/settings";
import { Tables } from "@/types/supabase";
import Image from "next/image";
import Link from "next/link";
import { auth } from "@clerk/nextjs/server";
import { Suspense } from "react";

type TeacherList = Tables<"Teacher"> & { subjects: Tables<"Subject">[] } & { classes: Tables<"Class">[] };

const TeacherListPage = async ({
  searchParams,
}: {
  searchParams: { [key: string]: string | undefined };
}) => {
  const { sessionClaims } = auth();
  const role = (sessionClaims?.metadata as { role?: string })?.role;
  const columns = [
    {
      header: "Info",
      accessor: "info",
    },
    {
      header: "Teacher ID",
      accessor: "teacherId",
      className: "hidden md:table-cell",
    },
    {
      header: "Subjects",
      accessor: "subjects",
      className: "hidden md:table-cell",
    },
    {
      header: "Classes",
      accessor: "classes",
      className: "hidden md:table-cell",
    },
    {
      header: "Phone",
      accessor: "phone",
      className: "hidden lg:table-cell",
    },
    {
      header: "Address",
      accessor: "address",
      className: "hidden lg:table-cell",
    },
    ...(role === "admin"
      ? [
        {
          header: "Actions",
          accessor: "action",
        },
      ]
      : []),
  ];

  const renderRow = (item: TeacherList) => (
    <tr
      key={item.id}
      className="border-b border-gray-200 even:bg-slate-50 text-sm hover:bg-lamaPurpleLight"
    >
      <td className="flex items-center gap-4 p-4">
        <Image
          src={item.img || "/noAvatar.png"}
          alt=""
          width={40}
          height={40}
          className="md:hidden xl:block w-10 h-10 rounded-full object-cover"
        />
        <div className="flex flex-col">
          <h3 className="font-semibold">{item.name}</h3>
          <p className="text-xs text-gray-500">{item?.email}</p>
        </div>
      </td>
      <td className="hidden md:table-cell">{item.username}</td>
      <td className="hidden md:table-cell">
        {item.subjects.map((subject) => subject.name).join(",")}
      </td>
      <td className="hidden md:table-cell">
        {item.classes.map((classItem) => classItem.name).join(",")}
      </td>
      <td className="hidden md:table-cell">{item.phone}</td>
      <td className="hidden md:table-cell">{item.address}</td>
      <td>
        <div className="flex items-center gap-2">
          <Link href={`/list/teachers/${item.id}`}>
            <button className="w-7 h-7 flex items-center justify-center rounded-full bg-lamaSky">
              <Image src="/view.png" alt="" width={16} height={16} />
            </button>
          </Link>
          {role === "admin" && (
            // <button className="w-7 h-7 flex items-center justify-center rounded-full bg-lamaPurple">
            //   <Image src="/delete.png" alt="" width={16} height={16} />
            // </button>
            <FormContainer table="teacher" type="delete" id={item.id} />
          )}
        </div>
      </td>
    </tr>
  );
  const { page, ...queryParams } = searchParams;

  const p = page ? parseInt(page) : 1;
  const supabase = await getSupabaseClient();

  const classesRes = await supabase.from("Class").select("id, name").order("name");
  const classOptions = (classesRes.data ?? []).map((c) => ({ value: String(c.id), label: c.name }));
  const sortOptions = [{ value: "name", label: "Name" }];
  const filters = [{ key: "classId", label: "Class", options: classOptions }];

  // URL PARAMS CONDITION
  let query = supabase
    .from("Teacher")
    .select("*, TeacherSubject(Subject(*)), classes:Class(*), lessons:Lesson(*)", { count: "exact" });

  if (queryParams) {
    for (const [key, value] of Object.entries(queryParams)) {
      if (value === undefined) continue;
      switch (key) {
        case "classId":
          query = query.eq("lessons.classId", parseInt(value));
          break;
        case "search":
          query = query.ilike("name", `%${value}%`);
          break;
        case "sortBy": {
          const col = value === "name" ? "name" : "name";
          const asc = queryParams.sortOrder !== "desc";
          query = query.order(col, { ascending: asc });
          break;
        }
        default:
          break;
      }
    }
  }
  if (!queryParams.sortBy) query = query.order("name", { ascending: true });

  // PAGINATION
  query = query.range(ITEM_PER_PAGE * (p - 1), ITEM_PER_PAGE * p - 1);

  let { data: rawData, count, error } = await query;

  if (error) {
    console.error("Error fetching teachers from Supabase:", error);
  }

  // Workaround for `classId` query:
  if (queryParams.classId && rawData) {
    rawData = rawData.filter(teacher =>
      // @ts-ignore
      teacher.lessons?.some((lesson: any) => lesson.classId === parseInt(queryParams.classId!))
    );
    count = rawData.length;
  }

  // Map the nested TeacherSubject data back to a flat subjects array for the datatable
  const data = (rawData || []).map(teacher => {
    // @ts-ignore
    const subjects = teacher.TeacherSubject?.map((rel: any) => rel.Subject) || [];
    return {
      ...teacher,
      subjects
    }
  }) as unknown as TeacherList[];

  return (
    <div className="bg-white p-4 rounded-md flex-1 m-4 mt-0">
      <div className="flex items-center justify-between">
        <h1 className="hidden md:block text-lg font-semibold">All Teachers</h1>
      </div>
      <Suspense fallback={<div className="py-3 border-b border-gray-200 animate-pulse" />}>
        <ListFilterSort sortOptions={sortOptions} filters={filters} showSearch>
          {role === "admin" && <FormContainer table="teacher" type="create" />}
        </ListFilterSort>
      </Suspense>
      <Table columns={columns} renderRow={renderRow} data={data} />
      {/* PAGINATION */}
      <Pagination page={p} count={count || 0} />
    </div>
  );
};

export default TeacherListPage;
