import { createClient } from "@/lib/supabase/server";
import { canDo } from "@/lib/auth/permissions";
import { PageHeader } from "@/components/layout/page-header";
import { Card } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { FeePaymentDialog } from "./fee-payment-dialog";

type FeePaymentRow = {
  id: string;
  payment_date: string;
  amount: number;
  currency: string | null;
  mode: string | null;
  reference: string | null;
  application: { applicant_name: string } | null;
};

export default async function FeePaymentsPage() {
  const supabase = await createClient();

  const [{ data: paymentsData }, { data: appsData }, { data: plansData }] =
    await Promise.all([
      supabase
        .from("fee_payments")
        .select("*, application:student_applications(applicant_name)")
        .order("payment_date", { ascending: false }),
      supabase
        .from("student_applications")
        .select("id, applicant_name")
        .order("created_at", { ascending: false })
        .limit(500),
      supabase.from("plans_sub").select("id, name, amount").order("name"),
    ]);

  const payments = (paymentsData as FeePaymentRow[]) ?? [];
  const applications =
    (appsData as { id: string; applicant_name: string }[]) ?? [];
  const plans =
    (plansData as { id: string; name: string; amount: number | null }[]) ?? [];

  const canManage = await canDo("finance", "update");
  const total = payments.reduce((sum, p) => sum + Number(p.amount ?? 0), 0);

  return (
    <div>
      <PageHeader
        title="Fee Payments"
        breadcrumb="Home / Fee Payments"
        action={
          canManage ? (
            <FeePaymentDialog applications={applications} plans={plans} />
          ) : undefined
        }
      />
      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>No</TableHead>
              <TableHead>Date</TableHead>
              <TableHead>Applicant</TableHead>
              <TableHead>Amount</TableHead>
              <TableHead>Mode</TableHead>
              <TableHead>Reference</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {payments.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={6}
                  className="py-10 text-center text-muted-foreground"
                >
                  No fee payments recorded yet.
                </TableCell>
              </TableRow>
            ) : (
              <>
                {payments.map((p, i) => (
                  <TableRow key={p.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell>{p.payment_date}</TableCell>
                    <TableCell>{p.application?.applicant_name ?? "—"}</TableCell>
                    <TableCell className="font-medium">
                      {Number(p.amount ?? 0).toLocaleString()} {p.currency ?? "INR"}
                    </TableCell>
                    <TableCell>{p.mode ?? "—"}</TableCell>
                    <TableCell>{p.reference ?? "—"}</TableCell>
                  </TableRow>
                ))}
                <TableRow>
                  <TableCell colSpan={3} className="text-right font-medium">
                    Total
                  </TableCell>
                  <TableCell className="font-semibold text-brand-blue">
                    {total.toLocaleString()}
                  </TableCell>
                  <TableCell colSpan={2} />
                </TableRow>
              </>
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
