import Link from "next/link";
import { ArrowRight, Receipt } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { formatDate, formatTRY } from "@/lib/format";
import { cn } from "@/lib/utils";

import type { DashboardData } from "@/lib/appwrite/dashboard-queries";

const TYPE_LABEL: Record<string, string> = {
  income: "Gelir",
  expense: "Gider",
  debt: "Borç",
  receivable: "Alacak",
};

const TYPE_COLOR: Record<string, string> = {
  income: "text-emerald-600 dark:text-emerald-400",
  expense: "text-red-600 dark:text-red-400",
  debt: "text-amber-600 dark:text-amber-400",
  receivable: "text-blue-600 dark:text-blue-400",
};

export function RecentTransactions({
  data,
}: {
  data: DashboardData["recentTransactions"];
}) {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <div>
          <CardTitle>Son işlemler</CardTitle>
          <CardDescription>En son finans hareketleri</CardDescription>
        </div>
        <Button asChild variant="ghost" size="sm">
          <Link href="/finance">
            Tümü <ArrowRight className="size-3.5" />
          </Link>
        </Button>
      </CardHeader>
      <CardContent>
        {data.length === 0 ? (
          <div className="text-muted-foreground flex flex-col items-center gap-2 py-10 text-sm">
            <Receipt className="size-6" />
            <p>Henüz finans hareketi yok.</p>
          </div>
        ) : (
          <ul className="divide-y">
            {data.map((t) => {
              const sign =
                t.type === "income" || t.type === "receivable" ? "+" : "−";
              return (
                <li key={t.id} className="flex items-center justify-between py-2.5">
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline" className="text-xs">
                        {TYPE_LABEL[t.type]}
                      </Badge>
                      <span className="text-muted-foreground text-xs">
                        {formatDate(t.date)}
                      </span>
                    </div>
                    <p className="mt-0.5 truncate text-sm">
                      {t.customerName ? `${t.customerName} — ` : ""}
                      {t.description || "—"}
                    </p>
                  </div>
                  <span className={cn("font-medium tabular-nums", TYPE_COLOR[t.type])}>
                    {sign} {formatTRY(t.amount)}
                  </span>
                </li>
              );
            })}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
