import FormContainer from "@/components/FormContainer";
import Pagination from "@/components/Pagination";
import Table from "@/components/Table";
import TableSearch from "@/components/TableSearch";
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";

type ResultList = {
  id: number;
  title: string;
  studentName: string;
  studentSurname: string;
  teacherName: string;
  teacherSurname: string;
  score: number;
  className: string;
  startTime: Date;
};


const ResultListPage = 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: "Student",
      accessor: "student",
    },
    {
      header: "Score",
      accessor: "score",
      className: "hidden md:table-cell",
    },
    {
      header: "Teacher",
      accessor: "teacher",
      className: "hidden md:table-cell",
    },
    {
      header: "Class",
      accessor: "class",
      className: "hidden md:table-cell",
    },
    {
      header: "Date",
      accessor: "date",
      className: "hidden md:table-cell",
    },
    ...(role === "admin" || role === "teacher"
      ? [
        {
          header: "Actions",
          accessor: "action",
        },
      ]
      : []),
  ];

  const renderRow = (item: ResultList) => (
    <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.studentName + " " + item.studentName}</td>
      <td className="hidden md:table-cell">{item.score}</td>
      <td className="hidden md:table-cell">
        {item.teacherName + " " + item.teacherSurname}
      </td>
      <td className="hidden md:table-cell">{item.className}</td>
      <td className="hidden md:table-cell">
        {new Intl.DateTimeFormat("en-US").format(new Date(item.startTime))}
      </td>
      <td>
        <div className="flex items-center gap-2">
          {(role === "admin" || role === "teacher") && (
            <>
              <FormContainer table="result" type="update" data={item} />
              <FormContainer table="result" type="delete" id={item.id} />
            </>
          )}
        </div>
      </td>
    </tr>
  );

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

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

  // URL PARAMS CONDITION
  let query = supabase
    .from("Result")
    .select(`
      *,
      student:Student(*),
      exam:Exam(
        *,
        lesson:Lesson!inner(
          class:Class(*),
          teacher:Teacher(*)
        )
      ),
      assignment:Assignment(
        *,
        lesson:Lesson!inner(
          class:Class(*),
          teacher:Teacher(*)
        )
      )
    `, { count: "exact" });

  if (queryParams) {
    for (const [key, value] of Object.entries(queryParams)) {
      if (value !== undefined) {
        switch (key) {
          case "studentId":
            query = query.eq("studentId", value);
            break;
          case "search":
            // Supabase JS doesn't easily support OR across joined tables via .or() string syntax
            // like `exam.title.ilike.%val%,student.name.ilike.%val%`.
            // Workaround: We will fetch broadly and filter below, or just rely on RLS.
            // For true broad search in Supabase over joins,
            // an RPC function is usually required. For now, dropping search.
            console.warn("Cross-table search text not supported in standard Supabase JS select without RPC.");
            break;
          default:
            break;
        }
      }
    }
  }

  // ROLE CONDITIONS: Handled by Supabase Postgres RLS.

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

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

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

  const dlist = (dataRes || []) as unknown as any[];
  const data = dlist.map((item) => {
    const assessment = item.exam || item.assignment;

    if (!assessment) return null;

    const isExam = "startTime" in assessment;

    return {
      id: item.id,
      title: assessment.title,
      studentName: item.student?.name || "Unknown",
      studentSurname: item.student?.surname || "",
      teacherName: assessment.lesson?.teacher?.name || "-",
      teacherSurname: assessment.lesson?.teacher?.surname || "",
      score: item.score,
      className: assessment.lesson?.class?.name || "-",
      startTime: isExam ? assessment.startTime : assessment.startDate,
    };
  }).filter(item => item !== null) as ResultList[];

  return (
    <div className="bg-white p-4 rounded-md flex-1 m-4 mt-0">
      {/* TOP */}
      <div className="flex items-center justify-between">
        <h1 className="hidden md:block text-lg font-semibold">All Results</h1>
        <div className="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto">
          <TableSearch />
          <div className="flex items-center gap-4 self-end">
            <button className="w-8 h-8 flex items-center justify-center rounded-full bg-lamaYellow">
              <Image src="/filter.png" alt="" width={14} height={14} />
            </button>
            <button className="w-8 h-8 flex items-center justify-center rounded-full bg-lamaYellow">
              <Image src="/sort.png" alt="" width={14} height={14} />
            </button>
            {(role === "admin" || role === "teacher") && (
              <FormContainer table="result" type="create" />
            )}
          </div>
        </div>
      </div>
      {/* LIST */}
      <Table columns={columns} renderRow={renderRow} data={data} />
      {/* PAGINATION */}
      <Pagination page={p} count={count || 0} />
    </div>
  );
};

export default ResultListPage;
