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

type EventList = Tables<"Event"> & { class: Tables<"Class"> | null };

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

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

  const columns = [
    {
      header: "Title",
      accessor: "title",
    },
    {
      header: "Class",
      accessor: "class",
    },
    {
      header: "Date",
      accessor: "date",
      className: "hidden md:table-cell",
    },
    {
      header: "Start Time",
      accessor: "startTime",
      className: "hidden md:table-cell",
    },
    {
      header: "End Time",
      accessor: "endTime",
      className: "hidden md:table-cell",
    },
    ...(role === "admin"
      ? [
        {
          header: "Actions",
          accessor: "action",
        },
      ]
      : []),
  ];

  const renderRow = (item: EventList) => (
    <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.title}</td>
      <td>{item.class?.name || "-"}</td>
      <td className="hidden md:table-cell">
        {new Intl.DateTimeFormat("en-US").format(new Date(item.startTime))}
      </td>
      <td className="hidden md:table-cell">
        {new Date(item.startTime).toLocaleTimeString("en-US", {
          hour: "2-digit",
          minute: "2-digit",
          hour12: false,
        })}
      </td>
      <td className="hidden md:table-cell">
        {new Date(item.endTime).toLocaleTimeString("en-US", {
          hour: "2-digit",
          minute: "2-digit",
          hour12: false,
        })}
      </td>
      <td>
        <div className="flex items-center gap-2">
          {role === "admin" && (
            <>
              <FormContainer table="event" type="update" data={item} />
              <FormContainer table="event" 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: "startTime", label: "Date" },
    { value: "title", label: "Title" },
  ];
  const filters = [{ key: "classId", label: "Class", options: classOptions }];

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

  if (queryParams) {
    for (const [key, value] of Object.entries(queryParams)) {
      if (value === undefined) continue;
      switch (key) {
        case "classId":
          if (value) query = query.eq("classId", parseInt(value));
          break;
        case "search":
          query = query.ilike("title", `%${value}%`);
          break;
        case "sortBy": {
          const col = value === "title" || value === "startTime" ? value : "startTime";
          const asc = queryParams.sortOrder !== "desc";
          query = query.order(col, { ascending: asc });
          break;
        }
        default:
          break;
      }
    }
  }
  if (!queryParams.sortBy) query = query.order("startTime", { 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 events from Supabase:", error);
  }

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

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

export default EventListPage;
