import Link from "next/link";
import {notFound, redirect} from "next/navigation";
import {auth} from "@/auth";
import {prisma} from "@/lib/db/prisma";
import {getTenantDb} from "@/lib/db/tenant";
import {Button} from "@/components/ui/button";
import {Plus} from "lucide-react";

export default async function InvoicesPage({params}: {params: Promise<{tenantSlug: string; locale: string}>}) {
  const {tenantSlug, locale} = await params;
  const session = await auth();
  if (!session?.user?.id) redirect(`/${locale}/auth/sign-in`);

  const tenant = await prisma.tenant.findUnique({where: {slug: tenantSlug}});
  if (!tenant) notFound();

  const db = getTenantDb(tenant.id);
  const invoices = await db.invoice.findMany({
    include: {booking: {select: {bookingNumber: true}}},
    orderBy: {createdAt: "desc"}
  });

  const statusColors: Record<string, string> = {
    DRAFT: "bg-slate-100 text-slate-600",
    ISSUED: "bg-blue-100 text-blue-700",
    PAID: "bg-green-100 text-green-700",
    PARTIALLY_PAID: "bg-yellow-100 text-yellow-700",
    OVERDUE: "bg-red-100 text-red-700"
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Invoices</h1>
          <p className="mt-1 text-slate-500">{invoices.length} invoices</p>
        </div>
        <Link href={`/${locale}/company/${tenantSlug}/invoices/new`}>
          <Button className="gap-2"><Plus className="h-4 w-4" />New Invoice</Button>
        </Link>
      </div>

      <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="px-3 py-3 text-left font-semibold">Invoice #</th>
              <th className="px-3 py-3 text-left font-semibold">Booking</th>
              <th className="px-3 py-3 text-left font-semibold">Issue Date</th>
              <th className="px-3 py-3 text-left font-semibold">Due Date</th>
              <th className="px-3 py-3 text-left font-semibold">Status</th>
              <th className="px-3 py-3 text-left font-semibold">Total</th>
              <th className="px-3 py-3 text-left font-semibold">Actions</th>
            </tr>
          </thead>
          <tbody>
            {invoices.map((inv) => (
              <tr key={inv.id} className="border-b border-slate-100 hover:bg-slate-50">
                <td className="px-3 py-3 font-mono text-xs">{inv.invoiceNumber}</td>
                <td className="px-3 py-3">{inv.booking?.bookingNumber || "—"}</td>
                <td className="px-3 py-3">{new Date(inv.issueDate).toLocaleDateString()}</td>
                <td className="px-3 py-3">{inv.dueDate ? new Date(inv.dueDate).toLocaleDateString() : "—"}</td>
                <td className="px-3 py-3">
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${statusColors[inv.status] || "bg-slate-100"}`}>
                    {inv.status.replace(/_/g, " ")}
                  </span>
                </td>
                <td className="px-3 py-3 font-semibold">{inv.currency} {Number(inv.totalAmount)}</td>
                <td className="px-3 py-3">
                  <Link href={`/${locale}/company/${tenantSlug}/invoices/${inv.id}`}>
                    <button className="rounded-lg border border-slate-200 px-2.5 py-1 text-xs font-medium hover:bg-slate-50">View</button>
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
