import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { formatCurrency } from "@/lib/utils";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";

export const metadata = { title: "Balance comptable" };

export default async function BalancePage() {
  const session = await auth();
  if (!session?.user?.id) redirect("/connexion");

  const membership = await prisma.organizationMember.findFirst({
    where: { userId: session.user.id, joinedAt: { not: null } },
    select: { organizationId: true },
  });
  if (!membership) redirect("/onboarding");

  const accounts = await prisma.chartOfAccount.findMany({
    where: { organizationId: membership.organizationId, isActive: true },
    include: {
      debitEntries: { select: { debitAmount: true } },
      creditEntries: { select: { creditAmount: true } },
    },
    orderBy: { code: "asc" },
  });

  const rows = accounts.map((a) => ({
    code: a.code,
    name: a.name,
    type: a.type,
    totalDebit: a.debitEntries.reduce((s, e) => s + Number(e.debitAmount), 0),
    totalCredit: a.creditEntries.reduce((s, e) => s + Number(e.creditAmount), 0),
  })).filter((r) => r.totalDebit > 0 || r.totalCredit > 0);

  const grandTotalDebit = rows.reduce((s, r) => s + r.totalDebit, 0);
  const grandTotalCredit = rows.reduce((s, r) => s + r.totalCredit, 0);
  const isBalanced = Math.abs(grandTotalDebit - grandTotalCredit) < 0.01;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Balance comptable</h1>
          <p className="text-sm text-muted-foreground">Vérification des mouvements débit/crédit</p>
        </div>
        <div className={cn("px-3 py-1 rounded-full text-xs font-semibold", isBalanced ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700")}>
          {isBalanced ? "Balance équilibrée" : "Balance déséquilibrée"}
        </div>
      </div>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Compte</TableHead>
              <TableHead>Intitulé</TableHead>
              <TableHead className="text-right">Total débit</TableHead>
              <TableHead className="text-right">Total crédit</TableHead>
              <TableHead className="text-right">Solde débiteur</TableHead>
              <TableHead className="text-right">Solde créditeur</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-12 text-muted-foreground">
                  Aucune écriture comptable enregistrée
                </TableCell>
              </TableRow>
            ) : (
              rows.map((r) => {
                const solde = r.totalDebit - r.totalCredit;
                return (
                  <TableRow key={r.code}>
                    <TableCell className="font-mono text-xs">{r.code}</TableCell>
                    <TableCell className="text-sm">{r.name}</TableCell>
                    <TableCell className="text-right tabular-nums text-sm">{formatCurrency(r.totalDebit)}</TableCell>
                    <TableCell className="text-right tabular-nums text-sm">{formatCurrency(r.totalCredit)}</TableCell>
                    <TableCell className="text-right tabular-nums text-sm">{solde > 0 ? formatCurrency(solde) : "—"}</TableCell>
                    <TableCell className="text-right tabular-nums text-sm">{solde < 0 ? formatCurrency(Math.abs(solde)) : "—"}</TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
          {rows.length > 0 && (
            <TableFooter>
              <TableRow className="font-bold">
                <TableCell colSpan={2}>TOTAUX</TableCell>
                <TableCell className="text-right tabular-nums">{formatCurrency(grandTotalDebit)}</TableCell>
                <TableCell className="text-right tabular-nums">{formatCurrency(grandTotalCredit)}</TableCell>
                <TableCell className="text-right tabular-nums">{formatCurrency(Math.max(0, grandTotalDebit - grandTotalCredit))}</TableCell>
                <TableCell className="text-right tabular-nums">{formatCurrency(Math.max(0, grandTotalCredit - grandTotalDebit))}</TableCell>
              </TableRow>
            </TableFooter>
          )}
        </Table>
      </Card>
    </div>
  );
}
