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 { Badge } from "@/components/ui/badge";
import { ArrowUpRight, ArrowDownRight } from "lucide-react";

export const metadata = { title: "Transactions" };

export default async function TransactionsPage() {
  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 transactions = await prisma.bankTransaction.findMany({
    where: { bankAccount: { organizationId: membership.organizationId } },
    orderBy: { date: "desc" },
    take: 50,
    include: { bankAccount: { select: { name: true } } },
  });

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Transactions</h1>
        <p className="text-sm text-muted-foreground">Toutes les transactions bancaires</p>
      </div>

      <Card>
        <CardContent className="p-0">
          {transactions.length === 0 ? (
            <div className="text-center py-16 text-muted-foreground">
              <p className="text-sm">Aucune transaction bancaire.</p>
              <p className="text-xs mt-1">Connectez un compte bancaire ou importez un relevé CSV.</p>
            </div>
          ) : (
            <div className="divide-y">
              {transactions.map((tx) => (
                <div key={tx.id} className="flex items-center justify-between px-6 py-4 hover:bg-muted/30 transition-colors">
                  <div className="flex items-center gap-3">
                    <div className={`h-8 w-8 rounded-full flex items-center justify-center ${tx.type === "INCOME" ? "bg-green-100 text-green-600" : "bg-red-100 text-red-600"}`}>
                      {tx.type === "INCOME" ? <ArrowUpRight className="h-4 w-4" /> : <ArrowDownRight className="h-4 w-4" />}
                    </div>
                    <div>
                      <p className="text-sm font-medium">{tx.description}</p>
                      <p className="text-xs text-muted-foreground">{tx.bankAccount.name} · {formatDate(tx.date)}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`font-semibold tabular-nums ${tx.type === "INCOME" ? "text-green-600" : "text-red-500"}`}>
                      {tx.type === "INCOME" ? "+" : "-"}{formatCurrency(Number(tx.amount))}
                    </p>
                    {tx.isReconciled && (
                      <Badge variant="success" className="text-[10px]">Rapproché</Badge>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
