import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { PaginationControl } from "@/components/ui/pagination-control";
import {
  APPLICATION_STATUSES,
  APPLICATION_STATUS_STYLES,
} from "@/lib/applications/constants";

const PAGE_SIZE = 20;

type ApplicationRow = {
  id: string;
  applicant_name: string;
  status: string;
  created_at: string;
  institute: { name: string } | { name: string }[] | null;
  type: { name: string } | { name: string }[] | null;
};

function oneName(
  rel: { name: string } | { name: string }[] | null | undefined,
): string {
  if (!rel) return "";
  const r = Array.isArray(rel) ? rel[0] : rel;
  return r?.name ?? "";
}

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export default async function StudentApplicationsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; page?: string }>;
}) {
  const sp = await searchParams;
  const status =
    sp.status && APPLICATION_STATUSES.includes(sp.status as never)
      ? sp.status
      : "";
  const page = Math.max(1, Number(sp.page) || 1);
  const from = (page - 1) * PAGE_SIZE;

  const supabase = await createClient();
  let query = supabase
    .from("student_applications")
    .select("*, institute:institutes(name), type:application_types(name)", {
      count: "exact",
    })
    .order("created_at", { ascending: false });
  if (status) query = query.eq("status", status);

  const { data, count } = await query.range(from, from + PAGE_SIZE - 1);
  const applications = (data as unknown as ApplicationRow[]) ?? [];

  return (
    <div>
      <PageHeader
        title="Student Application"
        breadcrumb="Application / Student Application"
        action={
          <Button asChild>
            <Link href="/applications/student/new">Add Student Application</Link>
          </Button>
        }
      />

      {/* Status filter chips (status comes through from dashboard cards too) */}
      <div className="mb-4 flex flex-wrap gap-2">
        <Button asChild size="sm" variant={status === "" ? "default" : "outline"}>
          <Link href="/applications/student">All</Link>
        </Button>
        {APPLICATION_STATUSES.map((s) => (
          <Button key={s} asChild size="sm" variant={status === s ? "default" : "outline"}>
            <Link href={`/applications/student?status=${encodeURIComponent(s)}`}>{s}</Link>
          </Button>
        ))}
      </div>

      <Card>
        <CardContent className="pt-6">
          {applications.length === 0 ? (
            <p className="text-sm text-muted-foreground">
              No student applications match this filter.
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">No</TableHead>
                  <TableHead>Applicant</TableHead>
                  <TableHead>Institute</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead className="text-right">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {applications.map((app, i) => (
                  <TableRow key={app.id}>
                    <TableCell>{from + i + 1}</TableCell>
                    <TableCell className="font-medium">
                      {app.applicant_name}
                    </TableCell>
                    <TableCell>{oneName(app.institute) || "—"}</TableCell>
                    <TableCell>{oneName(app.type) || "—"}</TableCell>
                    <TableCell>
                      <Badge
                        className={
                          APPLICATION_STATUS_STYLES[app.status] ??
                          "bg-gray-100 text-gray-800"
                        }
                      >
                        {app.status}
                      </Badge>
                    </TableCell>
                    <TableCell>{fmtDate(app.created_at)}</TableCell>
                    <TableCell className="text-right">
                      <Button asChild variant="link" className="h-auto p-0">
                        <Link href={`/applications/student/${app.id}`}>
                          View
                        </Link>
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <div className="mt-4">
        <PaginationControl page={page} pageSize={PAGE_SIZE} total={count ?? 0} />
      </div>
    </div>
  );
}
