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 { auth } from "@clerk/nextjs/server";
import { Suspense } from "react";

type ClassList = Tables<"Class"> & { supervisor: Tables<"Teacher"> | null };

const ClassListPage = async ({
  searchParams,
}: {
  searchParams: { [key: string]: string | undefined };
}) => {

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


  const columns = [
    {
      header: "Class Name",
      accessor: "name",
    },
    {
      header: "Capacity",
      accessor: "capacity",
      className: "hidden md:table-cell",
    },
    {
      header: "Grade",
      accessor: "grade",
      className: "hidden md:table-cell",
    },
    {
      header: "Supervisor",
      accessor: "supervisor",
      className: "hidden md:table-cell",
    },
    ...(role === "admin"
      ? [
        {
          header: "Actions",
          accessor: "action",
        },
      ]
      : []),
  ];

  const renderRow = (item: ClassList) => (
    <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">{item.name}</td>
      <td className="hidden md:table-cell">{item.capacity}</td>
      <td className="hidden md:table-cell">{item.name[0]}</td>
      <td className="hidden md:table-cell">
        {item.supervisor ? item.supervisor.name + " " + item.supervisor.surname : "-"}
      </td>
      <td>
        <div className="flex items-center gap-2">
          {role === "admin" && (
            <>
              <FormContainer table="class" type="update" data={item} />
              <FormContainer table="class" type="delete" id={item.id} />
            </>
          )}
        </div>
      </td>
    </tr>
  );

  const { page, ...queryParams } = searchParams;

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

  const teachersRes = await supabase.from("Teacher").select("id, name, surname").order("name");
  const teacherOptions = (teachersRes.data ?? []).map((t) => ({
    value: t.id,
    label: `${t.name} ${t.surname}`.trim(),
  }));
  const sortOptions = [{ value: "name", label: "Name" }];
  const filters = [{ key: "supervisorId", label: "Supervisor", options: teacherOptions }];

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

  if (queryParams) {
    for (const [key, value] of Object.entries(queryParams)) {
      if (value === undefined) continue;
      switch (key) {
        case "supervisorId":
          query = query.eq("supervisorId", 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);

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

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

  const data = (rawData || []) as unknown as ClassList[];

  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 Classes</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="class" type="create" />}
        </ListFilterSort>
      </Suspense>
      <Table columns={columns} renderRow={renderRow} data={data} />
      {/* PAGINATION */}
      <Pagination page={p} count={count || 0} />
    </div>
  );
};

export default ClassListPage;
