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 StudentList = Tables<"Student"> & {
  studentClasses: { classId: number; class: Tables<"Class"> }[];
};

const StudentListPage = 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: "Student ID",
      accessor: "studentId",
      className: "hidden md:table-cell",
    },
    {
      header: "Grade",
      accessor: "grade",
      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: StudentList) => {
    const classNames = item.studentClasses?.map((sc) => sc.class?.name).filter(Boolean).join(", ") || "-";
    const firstClassLetter = item.studentClasses?.[0]?.class?.name?.[0] ?? "-";
    return (
    <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">{classNames}</p>
        </div>
      </td>
      <td className="hidden md:table-cell">{item.username}</td>
      <td className="hidden md:table-cell">{firstClassLetter}</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/students/${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="student" type="delete" id={item.id} />
          )}
        </div>
      </td>
    </tr>
  );
  };

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

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

  const [classesRes, teachersRes] = await Promise.all([
    supabase.from("Class").select("id, name").order("name"),
    supabase.from("Teacher").select("id, name, surname").order("name"),
  ]);
  const classOptions = (classesRes.data ?? []).map((c) => ({ value: String(c.id), label: c.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: "classId", label: "Class", options: classOptions },
    { key: "teacherId", label: "Teacher", options: teacherOptions },
  ];

  let studentIdsFilter: string[] | null = null;
  if (queryParams.classId) {
    const { data: links } = await supabase.from("StudentClass").select("studentId").eq("classId", parseInt(queryParams.classId));
    studentIdsFilter = (links ?? []).map((l) => l.studentId);
    if (studentIdsFilter.length === 0) studentIdsFilter = [""];
  } else if (queryParams.teacherId) {
    const { data: lessonRows } = await supabase.from("Lesson").select("classId").eq("teacherId", queryParams.teacherId);
    const classIds = Array.from(new Set((lessonRows ?? []).map((r) => r.classId)));
    if (classIds.length > 0) {
      const { data: scRows } = await supabase.from("StudentClass").select("studentId").in("classId", classIds);
      studentIdsFilter = Array.from(new Set((scRows ?? []).map((r) => r.studentId)));
    }
    if (!studentIdsFilter || studentIdsFilter.length === 0) studentIdsFilter = [""];
  }

  let query = supabase
    .from("Student")
    .select("*, studentClasses:StudentClass(class:Class(*))", { count: "exact" });

  if (studentIdsFilter) query = query.in("id", studentIdsFilter);

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

  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 students from Supabase:", error);
  }

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

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

export default StudentListPage;
