import { redirect } from "next/navigation";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { listInboundJobs } from "@/lib/appwrite/job-queries";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { JobsFilterBar } from "../_components/jobs-filter-bar";
import { JobsTable } from "../_components/jobs-table";
import { BulkAcceptButton } from "./components/bulk-accept-button";

export const metadata = {
  title: "DLS — Gelen İşler",
};

export default async function InboundJobsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; location?: string; q?: string }>;
}) {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const sp = await searchParams;
  const filters = {
    status: sp.status && sp.status !== "all" ? sp.status : undefined,
    location: sp.location && sp.location !== "all" ? sp.location : undefined,
    q: sp.q,
  };
  const rows = ctx.kind === "lab" ? await listInboundJobs(ctx.tenantId, filters) : [];
  const pendingCount = rows.filter((j) => j.status === "pending").length;

  return (
    <div className="flex-1 space-y-6 px-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="flex flex-col gap-1">
          <h1 className="text-2xl font-bold tracking-tight">Gelen İşler</h1>
          <p className="text-muted-foreground text-sm">
            Bağlı kliniklerden size yönlendirilmiş protez işleri.
          </p>
        </div>
        {ctx.kind === "lab" && <BulkAcceptButton count={pendingCount} />}
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Tüm Gelen İşler</CardTitle>
          <CardDescription>
            {ctx.kind === "lab"
              ? rows.length === 0
                ? "Filtreye uyan iş yok."
                : `${rows.length} kalem`
              : "Bu sayfa laboratuvar hesapları içindir."}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {ctx.kind === "lab" ? (
            <>
              <JobsFilterBar />
              <JobsTable
                rows={rows}
                counterpartLabel="Klinik"
                emptyMessage="Filtreye uyan iş yok. Üstteki filtreleri değiştirin veya temizleyin."
              />
            </>
          ) : (
            <p className="text-muted-foreground py-6 text-center text-sm">
              Klinik hesabıyla giriş yaptınız — gelen iş listesi sadece laboratuvar tarafında görünür.
            </p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
