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

type InvoiceDetailPageProps = {
  params: Promise<{tenantSlug: string; invoiceId: string; locale: string}>;
};

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",
  VOID: "bg-gray-100 text-gray-500"
};

export default async function InvoiceDetailPage({params}: InvoiceDetailPageProps) {
  const {tenantSlug, invoiceId, 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 invoice = await db.invoice.findFirst({
    where: {id: invoiceId},
    include: {
      booking: {
        include: {
          vehicle: {include: {brand: true}},
          customerProfile: {
            include: {user: {select: {firstName: true, lastName: true, email: true, phone: true}}}
          },
          pickupBranch: true
        }
      },
      payments: {
        orderBy: {createdAt: "desc"}
      }
    }
  });

  if (!invoice) notFound();

  const user = invoice.booking.customerProfile.user;
  const customerName = user.firstName
    ? `${user.firstName} ${user.lastName ?? ""}`.trim()
    : user.email;
  const vehicle = invoice.booking.vehicle;

  return (
    <div className="mx-auto max-w-4xl space-y-6">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <Link
            href={`/company/${tenantSlug}/invoices`}
            className="mb-3 inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 transition"
          >
            ← Back to Invoices
          </Link>
          <h1 className="text-2xl font-bold text-slate-900">Invoice {invoice.invoiceNumber}</h1>
          <p className="mt-1 text-slate-500">
            Issued: {new Date(invoice.issueDate).toLocaleDateString()}
            {invoice.dueDate && ` · Due: ${new Date(invoice.dueDate).toLocaleDateString()}`}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <span
            className={`rounded-full px-3 py-1 text-sm font-medium ${statusColors[invoice.status] ?? "bg-slate-100"}`}
          >
            {invoice.status.replace(/_/g, " ")}
          </span>
          <PrintButton label="Print" />
        </div>
      </div>

      {/* Invoice card */}
      <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm print:border-0 print:shadow-none">
        {/* Company + Customer header */}
        <div className="flex justify-between border-b border-slate-100 pb-6">
          <div>
            <p className="text-lg font-bold text-slate-900">{tenant.name}</p>
            {tenant.email && <p className="text-sm text-slate-500">{tenant.email}</p>}
            {tenant.phone && <p className="text-sm text-slate-500">{tenant.phone}</p>}
          </div>
          <div className="text-right">
            <p className="text-sm font-semibold text-slate-700">Bill To</p>
            <p className="text-sm text-slate-900">{customerName}</p>
            <p className="text-sm text-slate-500">{user.email}</p>
            {user.phone && <p className="text-sm text-slate-500">{user.phone}</p>}
          </div>
        </div>

        {/* Invoice details */}
        <div className="mt-6 grid grid-cols-2 gap-4 border-b border-slate-100 pb-6 sm:grid-cols-4">
          <div>
            <p className="text-xs font-medium text-slate-500 uppercase tracking-wide">Invoice #</p>
            <p className="mt-1 font-mono text-sm font-semibold text-slate-900">{invoice.invoiceNumber}</p>
          </div>
          <div>
            <p className="text-xs font-medium text-slate-500 uppercase tracking-wide">Booking #</p>
            <p className="mt-1 font-mono text-sm text-slate-900">{invoice.booking.bookingNumber}</p>
          </div>
          <div>
            <p className="text-xs font-medium text-slate-500 uppercase tracking-wide">Issue Date</p>
            <p className="mt-1 text-sm text-slate-900">{new Date(invoice.issueDate).toLocaleDateString()}</p>
          </div>
          {invoice.dueDate && (
            <div>
              <p className="text-xs font-medium text-slate-500 uppercase tracking-wide">Due Date</p>
              <p className="mt-1 text-sm text-slate-900">{new Date(invoice.dueDate).toLocaleDateString()}</p>
            </div>
          )}
        </div>

        {/* Line items */}
        <div className="mt-6 border-b border-slate-100 pb-6">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="py-2 text-left font-semibold text-slate-700">Description</th>
                <th className="py-2 text-right font-semibold text-slate-700">Amount</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td className="py-3 text-slate-900">
                  {vehicle.brand.name} {vehicle.name} — {Number(invoice.booking.rentalDays)} day(s)
                  <p className="text-xs text-slate-400">
                    {new Date(invoice.booking.pickupAt).toLocaleDateString()} →{" "}
                    {new Date(invoice.booking.dropoffAt).toLocaleDateString()}
                  </p>
                </td>
                <td className="py-3 text-right text-slate-900">
                  {invoice.currency} {Number(invoice.subtotal).toFixed(2)}
                </td>
              </tr>
              {Number(invoice.discountAmount) > 0 && (
                <tr>
                  <td className="py-2 text-slate-600">Discount</td>
                  <td className="py-2 text-right text-green-600">
                    − {invoice.currency} {Number(invoice.discountAmount).toFixed(2)}
                  </td>
                </tr>
              )}
              {Number(invoice.taxAmount) > 0 && (
                <tr>
                  <td className="py-2 text-slate-600">Tax</td>
                  <td className="py-2 text-right text-slate-900">
                    {invoice.currency} {Number(invoice.taxAmount).toFixed(2)}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Totals */}
        <div className="mt-4 flex justify-end">
          <div className="w-64 space-y-2">
            <div className="flex justify-between text-sm text-slate-600">
              <span>Subtotal</span>
              <span>
                {invoice.currency} {Number(invoice.subtotal).toFixed(2)}
              </span>
            </div>
            {Number(invoice.discountAmount) > 0 && (
              <div className="flex justify-between text-sm text-green-600">
                <span>Discount</span>
                <span>− {Number(invoice.discountAmount).toFixed(2)}</span>
              </div>
            )}
            {Number(invoice.taxAmount) > 0 && (
              <div className="flex justify-between text-sm text-slate-600">
                <span>Tax</span>
                <span>{Number(invoice.taxAmount).toFixed(2)}</span>
              </div>
            )}
            <div className="flex justify-between border-t border-slate-200 pt-2 font-bold text-slate-900">
              <span>Total</span>
              <span>
                {invoice.currency} {Number(invoice.totalAmount).toFixed(2)}
              </span>
            </div>
            {Number(invoice.paidAmount) > 0 && (
              <div className="flex justify-between text-sm text-green-600">
                <span>Paid</span>
                <span>− {Number(invoice.paidAmount).toFixed(2)}</span>
              </div>
            )}
            <div className="flex justify-between text-sm font-semibold text-slate-900">
              <span>Balance Due</span>
              <span>
                {invoice.currency}{" "}
                {(Number(invoice.totalAmount) - Number(invoice.paidAmount)).toFixed(2)}
              </span>
            </div>
          </div>
        </div>

        {invoice.notes && (
          <div className="mt-6 rounded-lg bg-slate-50 p-4 text-sm text-slate-600">
            <p className="font-medium text-slate-700">Notes</p>
            <p className="mt-1">{invoice.notes}</p>
          </div>
        )}
      </div>

      {/* Payments history */}
      {invoice.payments.length > 0 && (
        <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <h2 className="mb-4 font-semibold text-slate-900">Payment History</h2>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-100 text-left">
                <th className="py-2 font-semibold text-slate-700">Date</th>
                <th className="py-2 font-semibold text-slate-700">Method</th>
                <th className="py-2 font-semibold text-slate-700">Reference</th>
                <th className="py-2 text-right font-semibold text-slate-700">Amount</th>
                <th className="py-2 font-semibold text-slate-700">Status</th>
              </tr>
            </thead>
            <tbody>
              {invoice.payments.map((pmt) => (
                <tr key={pmt.id} className="border-b border-slate-50">
                  <td className="py-2 text-slate-600">
                    {pmt.paidAt ? new Date(pmt.paidAt).toLocaleDateString() : "—"}
                  </td>
                  <td className="py-2 text-slate-600">{pmt.method.replace(/_/g, " ")}</td>
                  <td className="py-2 font-mono text-xs text-slate-500">
                    {pmt.providerReference ?? "—"}
                  </td>
                  <td className="py-2 text-right font-semibold text-slate-900">
                    {pmt.currency} {Number(pmt.amount).toFixed(2)}
                  </td>
                  <td className="py-2">
                    <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">
                      {pmt.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
