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

export const metadata = { title: "Grand livre" };

export default async function GrandLivrePage() {
  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: { include: { journalEntry: { select: { date: true, description: true, number: true } } } },
      creditEntries: { include: { journalEntry: { select: { date: true, description: true, number: true } } } },
    },
    orderBy: { code: "asc" },
    take: 20,
  });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Grand livre</h1>
        <p className="text-sm text-muted-foreground">Détail des mouvements par compte</p>
      </div>

      {accounts.length === 0 ? (
        <Card>
          <CardContent className="flex items-center justify-center py-16">
            <p className="text-muted-foreground text-sm">Aucun compte comptable disponible</p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {accounts.slice(0, 10).map((account) => {
            const totalDebit = account.debitEntries.reduce((s, e) => s + Number(e.debitAmount), 0);
            const totalCredit = account.creditEntries.reduce((s, e) => s + Number(e.creditAmount), 0);
            const solde = totalDebit - totalCredit;
            if (totalDebit === 0 && totalCredit === 0) return null;

            return (
              <Card key={account.id}>
                <CardHeader className="pb-3">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-sm font-mono">
                      {account.code} — {account.name}
                    </CardTitle>
                    <span className={`text-sm font-semibold tabular-nums ${solde >= 0 ? "text-green-600" : "text-red-500"}`}>
                      Solde: {formatCurrency(solde)}
                    </span>
                  </div>
                </CardHeader>
                <CardContent className="p-0">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="pl-6">Date</TableHead>
                        <TableHead>Libellé</TableHead>
                        <TableHead className="text-right">Débit</TableHead>
                        <TableHead className="text-right pr-6">Crédit</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {account.debitEntries.map((e) => (
                        <TableRow key={e.id}>
                          <TableCell className="pl-6 text-xs">{formatDate(e.journalEntry.date)}</TableCell>
                          <TableCell className="text-xs">{e.journalEntry.description}</TableCell>
                          <TableCell className="text-right text-xs font-mono">{formatCurrency(Number(e.debitAmount))}</TableCell>
                          <TableCell className="text-right pr-6 text-xs text-muted-foreground">—</TableCell>
                        </TableRow>
                      ))}
                      {account.creditEntries.map((e) => (
                        <TableRow key={e.id}>
                          <TableCell className="pl-6 text-xs">{formatDate(e.journalEntry.date)}</TableCell>
                          <TableCell className="text-xs">{e.journalEntry.description}</TableCell>
                          <TableCell className="text-right text-xs text-muted-foreground">—</TableCell>
                          <TableCell className="text-right pr-6 text-xs font-mono">{formatCurrency(Number(e.creditAmount))}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
