import { redirect } from "next/navigation";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { listPatients } from "@/lib/appwrite/patient-queries";
import { requireTenant, requireTenantKind } from "@/lib/appwrite/tenant-guard";
import { PatientForm } from "./components/patient-form";
import { PatientsTable } from "./components/patients-table";

export const metadata = {
  title: "DLS — Hastalar",
};

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

  const rows = await listPatients(ctx.tenantId, { includeArchived: true });

  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">Hastalar</h1>
        <p className="text-muted-foreground text-sm">
          Kliniğinizin hasta defteri. Laboratuvar tarafında yalnızca hasta kodunu görür — kişisel veriler sizinle kalır.
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
        <Card>
          <CardHeader>
            <CardTitle>Hasta Listesi</CardTitle>
            <CardDescription>
              {rows.length === 0 ? "Henüz hasta yok." : `${rows.length} kayıt`}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <PatientsTable rows={rows} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Hasta Ekle</CardTitle>
            <CardDescription>
              Protokol numarası varsa girin, yoksa sistem 6 haneli benzersiz kod üretir.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <PatientForm />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
