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

type SchoolTimetableRow = Tables<"SchoolTimetable"> & {
    academicYear: Tables<"AcademicYear"> | null;
};

const SchoolTimetablesListPage = async ({
    searchParams,
}: {
    searchParams: { [key: string]: string | undefined };
}) => {
    const { sessionClaims } = auth();
    const schoolId = (sessionClaims?.metadata as { schoolId?: string })?.schoolId;

    const columns = [
        { header: "Timetable Name", accessor: "name" },
        { header: "Academic Year", accessor: "academicYear", className: "hidden md:table-cell" },
        { header: "View Slots", accessor: "viewSlots" },
    ];

    const renderRow = (item: SchoolTimetableRow) => (
        <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 font-medium">{item.name}</td>
            <td className="hidden md:table-cell text-gray-600">
                {item.academicYear ? item.academicYear.name : "—"}
            </td>
            <td>
                <Link
                    href={`/list/timeslots?schoolTimetableId=${item.id}`}
                    className="text-blue-500 hover:underline text-sm"
                >
                    View slots
                </Link>
            </td>
        </tr>
    );

    const { page, ...queryParams } = searchParams;
    const p = page ? parseInt(page) : 1;
    const supabase = await getSupabaseClient();

    let query = supabase
        .from("SchoolTimetable")
        .select("*, academicYear:AcademicYear(*)", { count: "exact" })
        .order("id", { ascending: true });

    if (schoolId) {
        query = query.eq("schoolId", schoolId);
    }

    if (queryParams.search) {
        query = query.or(`name.ilike.%${queryParams.search}%`);
    }

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

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

    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">School Timetables</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>
                    </div>
                </div>
            </div>
            <p className="text-sm text-gray-500 mt-1 mb-2">
                Each timetable defines the weekly slot layout for an academic year. Slots are managed under Timetable Slots.
            </p>
            <Table columns={columns} renderRow={renderRow} data={data} />
            <Pagination page={p} count={count || 0} />
        </div>
    );
};

export default SchoolTimetablesListPage;
