import Link from "next/link";
import { requireUser } from "@/lib/auth/session";
import { createClient } from "@/lib/supabase/server";
import { APPLICATION_STATUS_STYLES } from "@/lib/applications/constants";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { StudentApplication } from "@/lib/types";

export default async function PartnerApplicationsPage() {
  const user = await requireUser();
  const supabase = await createClient();

  const { data } = await supabase
    .from("student_applications")
    .select(
      "id, applicant_name, status, country, intake_month, intake_year, profile_completed_at, invite_sent_at, created_at, institute:institutes(name)",
    )
    .eq("partner_id", user.id)
    .order("created_at", { ascending: false });

  const apps = (data ?? []) as (Pick<
    StudentApplication,
    | "id"
    | "applicant_name"
    | "status"
    | "country"
    | "intake_month"
    | "intake_year"
    | "profile_completed_at"
    | "invite_sent_at"
    | "created_at"
  > & {
    institute: { name: string } | { name: string }[] | null;
  })[];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="font-heading text-2xl font-bold text-brand-navy">
          My Applications
        </h1>
        <Button asChild className="bg-brand-orange hover:bg-brand-orange/90">
          <Link href="/partner/applications/new">Submit application</Link>
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">
            {apps.length} {apps.length === 1 ? "application" : "applications"}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {apps.length === 0 ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              No applications yet. Submit your first student application.
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">No</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Institute</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Student profile</TableHead>
                  <TableHead>Submitted</TableHead>
                  <TableHead />
                </TableRow>
              </TableHeader>
              <TableBody>
                {apps.map((app, i) => {
                  const institute = Array.isArray(app.institute)
                    ? app.institute[0]?.name
                    : app.institute?.name;
                  const profileLabel = app.profile_completed_at
                    ? "Complete"
                    : app.invite_sent_at
                      ? "Pending"
                      : "Not invited";
                  return (
                    <TableRow key={app.id}>
                      <TableCell className="text-muted-foreground">{i + 1}</TableCell>
                      <TableCell className="font-medium">{app.applicant_name}</TableCell>
                      <TableCell>{institute ?? "—"}</TableCell>
                      <TableCell>
                        <span
                          className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
                            APPLICATION_STATUS_STYLES[app.status] ??
                            "bg-gray-100 text-gray-800"
                          }`}
                        >
                          {app.status}
                        </span>
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {profileLabel}
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {new Date(app.created_at).toLocaleDateString()}
                      </TableCell>
                      <TableCell>
                        <Button asChild variant="link" size="sm" className="px-0">
                          <Link href={`/partner/applications/${app.id}`}>View</Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
