import Link from "next/link";
import { Plus, Pencil } from "lucide-react";
import { createClient } from "@/lib/supabase/server";
import { canDo } from "@/lib/auth/permissions";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { EducationLoanInquiry } from "@/lib/types";

type InquiryRow = EducationLoanInquiry & {
  status: { name: string } | null;
};

function fmtAmount(amount: number | null, currency: string | null) {
  if (amount == null) return "—";
  const n = Number(amount).toLocaleString("en-IN");
  return `${currency ?? "INR"} ${n}`;
}

export default async function LoanInquiryPage() {
  const supabase = await createClient();
  const { data } = await supabase
    .from("education_loan_inquiries")
    .select("*, status:education_loan_statuses(name)")
    .order("created_at", { ascending: false });
  const inquiries = (data as InquiryRow[] | null) ?? [];
  const canManage = await canDo("loan", "update");

  return (
    <div>
      <PageHeader
        title="Education Loan Inquiry"
        breadcrumb="Home / Loan Inquiry"
        action={
          canManage ? (
            <Button asChild>
              <Link href="/loan-inquiry/new">
                <Plus className="size-4" /> Add Inquiry
              </Link>
            </Button>
          ) : undefined
        }
      />
      <Card className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">No</TableHead>
              <TableHead>Applicant</TableHead>
              <TableHead>Bank</TableHead>
              <TableHead>Amount</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Sanctioned</TableHead>
              <TableHead className="text-right">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {inquiries.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={7}
                  className="py-10 text-center text-muted-foreground"
                >
                  No loan inquiries yet.
                </TableCell>
              </TableRow>
            ) : (
              inquiries.map((row, i) => (
                <TableRow key={row.id}>
                  <TableCell>{i + 1}</TableCell>
                  <TableCell className="font-medium">
                    {row.applicant_name}
                  </TableCell>
                  <TableCell>{row.bank_name ?? "—"}</TableCell>
                  <TableCell>{fmtAmount(row.amount, row.currency)}</TableCell>
                  <TableCell>
                    {row.status?.name ? (
                      <Badge variant="secondary">{row.status.name}</Badge>
                    ) : (
                      "—"
                    )}
                  </TableCell>
                  <TableCell>{row.sanctioned_date ?? "—"}</TableCell>
                  <TableCell className="text-right">
                    <Button asChild variant="ghost" size="sm">
                      <Link href={`/loan-inquiry/${row.id}/edit`}>
                        <Pencil className="size-4" /> Edit
                      </Link>
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>
    </div>
  );
}
