import { redirect } from "next/navigation";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { listFinanceEntries, summarizeFinance } from "@/lib/appwrite/finance-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { FinanceTable } from "./components/finance-table";

export const metadata = {
  title: "DLS — Finans",
};

function formatMoney(amount: number, currency: string): string {
  try {
    return new Intl.NumberFormat("tr-TR", { style: "currency", currency }).format(amount);
  } catch {
    return `${amount.toFixed(2)} ${currency}`;
  }
}

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

  const entries = await listFinanceEntries(ctx.tenantId);
  const stats = summarizeFinance(entries);
  const isLab = ctx.kind === "lab";

  return (
    <div className="flex-1 space-y-6 px-6">
      <div className="flex flex-col gap-1">
        <h1 className="text-2xl font-bold tracking-tight">Finans</h1>
        <p className="text-muted-foreground text-sm">
          İş bazlı tahsilat ve ödeme akışı. {isLab ? "Alacaklarınız ve gelirleriniz." : "Ödenecek ve harcamalarınız."}
        </p>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={isLab ? "Bekleyen Alacak" : "Bekleyen Borç"}
          value={formatMoney(isLab ? stats.receivablePending : stats.payablePending, stats.currency)}
          tone={isLab ? "positive" : "negative"}
        />
        <StatCard
          label="Bu Ay Gelir"
          value={formatMoney(stats.incomeThisMonth, stats.currency)}
          tone="positive"
        />
        <StatCard
          label="Bu Ay Gider"
          value={formatMoney(stats.expenseThisMonth, stats.currency)}
          tone="negative"
        />
        <StatCard
          label="Toplam Kayıt"
          value={String(entries.length)}
          tone="neutral"
        />
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Hareketler</CardTitle>
          <CardDescription>
            Tamamlanan işlerden otomatik oluşturulan finansal kayıtlar. Manuel kayıt eklemek sonraki sürümde.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <FinanceTable rows={entries} />
        </CardContent>
      </Card>
    </div>
  );
}

function StatCard({
  label,
  value,
  tone,
}: {
  label: string;
  value: string;
  tone: "positive" | "negative" | "neutral";
}) {
  const color =
    tone === "positive"
      ? "text-emerald-600 dark:text-emerald-400"
      : tone === "negative"
        ? "text-rose-600 dark:text-rose-400"
        : "text-foreground";
  return (
    <Card>
      <CardHeader className="pb-2">
        <CardDescription className="text-xs uppercase tracking-wide">
          {label}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <p className={`text-2xl font-semibold tabular-nums ${color}`}>{value}</p>
      </CardContent>
    </Card>
  );
}
