import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { listCustomers } from "@/lib/appwrite/customer-queries";
import { getInvoice, listInvoiceItems } from "@/lib/appwrite/invoice-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { formatDate, formatTRY } from "@/lib/format";
import { cn } from "@/lib/utils";

import { STATUS_COLOR, STATUS_LABEL } from "../components/types";
import { InvoiceItemsEditor } from "./components/items-editor";
import { InvoiceHeaderActions } from "./components/header-actions";

export const metadata: Metadata = {
  title: "İşletmem — Fatura",
};

export default async function InvoiceDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const invoice = await getInvoice(ctx.tenantId, id);
  if (!invoice) notFound();

  const [items, customers] = await Promise.all([
    listInvoiceItems(ctx.tenantId, id),
    listCustomers(ctx.tenantId),
  ]);

  const customerName = customers.find((c) => c.$id === invoice.customerId)?.name ?? "—";

  return (
    <div className="flex-1 space-y-6 px-6 pt-0">
      <div className="flex items-center gap-2">
        <Button asChild variant="ghost" size="sm">
          <Link href="/invoices">
            <ArrowLeft className="size-3.5" />
            Faturalar
          </Link>
        </Button>
      </div>

      <div className="flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
        <div>
          <p className="text-muted-foreground text-sm">{customerName}</p>
          <h1 className="font-mono text-2xl font-bold tracking-tight">{invoice.number}</h1>
          <div className="mt-2 flex flex-wrap items-center gap-3 text-sm">
            <span
              className={cn(
                "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs",
                STATUS_COLOR[invoice.status ?? "draft"],
              )}
            >
              {STATUS_LABEL[invoice.status ?? "draft"]}
            </span>
            <span className="text-muted-foreground">
              Düzenleme: {formatDate(invoice.issueDate)}
            </span>
            <span className="text-muted-foreground">Vade: {formatDate(invoice.dueDate)}</span>
          </div>
        </div>
        <InvoiceHeaderActions
          invoice={{
            id: invoice.$id,
            number: invoice.number,
            customerId: invoice.customerId,
            customerName,
            issueDate: invoice.issueDate,
            dueDate: invoice.dueDate,
            status: invoice.status ?? "draft",
            subtotal: invoice.subtotal ?? 0,
            vatTotal: invoice.vatTotal ?? 0,
            total: invoice.total ?? 0,
            notes: invoice.notes ?? "",
          }}
          customers={customers.map((c) => ({ id: c.$id, name: c.name }))}
        />
      </div>

      <InvoiceItemsEditor
        invoiceId={id}
        items={items.map((it) => ({
          id: it.$id,
          description: it.description,
          quantity: it.quantity,
          unitPrice: it.unitPrice,
          vatRate: it.vatRate ?? 0,
          lineTotal: it.lineTotal,
        }))}
      />

      <Card>
        <CardContent className="space-y-2 p-4">
          <div className="flex justify-between text-sm">
            <span className="text-muted-foreground">Ara toplam</span>
            <span className="tabular-nums">{formatTRY(invoice.subtotal ?? 0)}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-muted-foreground">KDV</span>
            <span className="tabular-nums">{formatTRY(invoice.vatTotal ?? 0)}</span>
          </div>
          <div className="border-t pt-2"></div>
          <div className="flex justify-between text-base font-semibold">
            <span>Genel toplam</span>
            <span className="tabular-nums">{formatTRY(invoice.total ?? 0)}</span>
          </div>
        </CardContent>
      </Card>

      {invoice.notes && (
        <Card>
          <CardContent className="p-4">
            <p className="text-muted-foreground text-xs font-medium uppercase">Notlar</p>
            <p className="mt-1 whitespace-pre-line text-sm">{invoice.notes}</p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
