import type { Metadata } from "next";
import { redirect } from "next/navigation";

import { listBankAccounts } from "@/lib/appwrite/bank-account-queries";
import { listAllInstallments, listLoans } from "@/lib/appwrite/loan-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { LoansClient } from "./components/loans-client";

export const metadata: Metadata = {
  title: "İşletmem — Krediler",
};

export default async function LoansPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const [loans, installments, bankAccounts] = await Promise.all([
    listLoans(ctx.tenantId, ctx.user.id),
    listAllInstallments(ctx.tenantId, ctx.user.id),
    listBankAccounts(ctx.tenantId, ctx.user.id),
  ]);

  const bankMap = new Map(
    bankAccounts.map((b) => [b.$id, `${b.bankName} — ${b.accountName}`]),
  );

  // Aggregate installment metrics per loan
  const byLoan = new Map<
    string,
    { totalAmount: number; paidAmount: number; nextDue: string | null; remainingCount: number }
  >();
  for (const inst of installments) {
    const cur = byLoan.get(inst.loanId) ?? {
      totalAmount: 0,
      paidAmount: 0,
      nextDue: null,
      remainingCount: 0,
    };
    cur.totalAmount += inst.amount ?? 0;
    if (inst.paid) {
      cur.paidAmount += inst.amount ?? 0;
    } else {
      cur.remainingCount += 1;
      if (!cur.nextDue || new Date(inst.dueDate).getTime() < new Date(cur.nextDue).getTime()) {
        cur.nextDue = inst.dueDate;
      }
    }
    byLoan.set(inst.loanId, cur);
  }

  return (
    <div className="flex-1 space-y-6 px-6 pt-0">
      <div className="flex flex-col gap-1">
        <p className="text-muted-foreground text-sm">{ctx.settings?.companyName ?? "Çalışma alanı"}</p>
        <h1 className="text-2xl font-bold tracking-tight">Krediler</h1>
        <p className="text-muted-foreground text-sm">
          Banka kredilerinizi ve taksit planlarını takip edin. Taksit ödendiğinde otomatik gider
          kaydı oluşur.
        </p>
      </div>

      <LoansClient
        loans={loans.map((l) => {
          const m = byLoan.get(l.$id) ?? {
            totalAmount: 0,
            paidAmount: 0,
            nextDue: null,
            remainingCount: 0,
          };
          return {
            id: l.$id,
            bankName: l.bankName,
            loanName: l.loanName,
            loanType: l.loanType ?? "consumer",
            principal: l.principal,
            interestRate: l.interestRate,
            termMonths: l.termMonths,
            monthlyPayment: l.monthlyPayment ?? 0,
            startDate: l.startDate,
            paymentDay: l.paymentDay ?? 1,
            status: l.status ?? "active",
            bankAccountId: l.bankAccountId ?? "",
            bankAccountLabel: l.bankAccountId ? bankMap.get(l.bankAccountId) ?? "" : "",
            notes: l.notes ?? "",
            totalAmount: m.totalAmount,
            paidAmount: m.paidAmount,
            remainingCount: m.remainingCount,
            nextDue: m.nextDue,
            scope: (l.scope ?? "company") as "company" | "personal",
          };
        })}
        installments={installments.map((i) => ({
          id: i.$id,
          loanId: i.loanId,
          installmentNo: i.installmentNo,
          dueDate: i.dueDate,
          amount: i.amount,
          principalPart: i.principalPart ?? 0,
          interestPart: i.interestPart ?? 0,
          paid: Boolean(i.paid),
          paidAt: i.paidAt ?? "",
        }))}
        bankAccounts={bankAccounts
          .filter((b) => !b.archived)
          .map((b) => ({
            id: b.$id,
            label: `${b.bankName} — ${b.accountName}`,
          }))}
      />
    </div>
  );
}
