import { redirect } from "next/navigation";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { listProsthetics } from "@/lib/appwrite/prosthetic-queries";
import { requireTenant, requireTenantKind } from "@/lib/appwrite/tenant-guard";
import { ProstheticForm } from "./components/prosthetic-form";
import { ProstheticsTable } from "./components/prosthetics-table";

export const metadata = {
  title: "DLS — Ürünler",
};

export default async function ProductsPage() {
  let ctx;
  try {
    ctx = await requireTenant();
    requireTenantKind(ctx, ["lab"]);
  } catch {
    redirect("/dashboard");
  }

  const rows = await listProsthetics(ctx.tenantId);
  const defaultCurrency = ctx.settings?.defaultCurrency ?? "TRY";

  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">Ürünler</h1>
        <p className="text-muted-foreground text-sm">
          Sunduğunuz protez türleri ve fiyatlandırma katalogu. Klinikler iş yayınlarken bu listeden seçebilir.
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
        <Card>
          <CardHeader>
            <CardTitle>Eklenen Ürünler</CardTitle>
            <CardDescription>
              {rows.length === 0 ? "Henüz ürün yok." : `${rows.length} kalem`}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ProstheticsTable rows={rows} defaultCurrency={defaultCurrency} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Ürün Ekle</CardTitle>
            <CardDescription>Protez türü ve birim fiyatını girin.</CardDescription>
          </CardHeader>
          <CardContent>
            <ProstheticForm defaultCurrency={defaultCurrency} />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
