import { redirect } from "next/navigation";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { listClinicPricing } from "@/lib/appwrite/clinic-pricing-queries";
import {
  listApprovedConnections,
  listPendingInbound,
  listPendingOutbound,
} from "@/lib/appwrite/connection-queries";
import type { ClinicPricing } from "@/lib/appwrite/schema";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import { ConnectionCodeCard } from "./components/connection-code-card";
import { ConnectionRequestForm } from "./components/connection-request-form";
import { PendingInboundTable } from "./components/pending-inbound-table";
import { PendingOutboundTable } from "./components/pending-outbound-table";
import { ConnectionsTable } from "./components/connections-table";

export const metadata = {
  title: "DLS — Bağlantı Kur",
};

export default async function ConnectionsPage() {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    redirect("/onboarding");
  }

  const memberNumber = ctx.settings?.memberNumber ?? "";
  const isLab = ctx.kind === "lab";
  const counterpartLabel = isLab ? "klinik" : "laboratuvar";

  const [approved, pendingInbound, pendingOutbound] = await Promise.all([
    listApprovedConnections(ctx.tenantId),
    listPendingInbound(ctx.tenantId, ctx.user.id),
    listPendingOutbound(ctx.tenantId, ctx.user.id),
  ]);

  // Lab side: load pricing rules per approved clinic so the dialog can
  // surface existing rules. Clinic side leaves this empty — it's display-only
  // for them (see ConnectionsTable).
  const pricingByCounterpart = new Map<string, ClinicPricing[]>();
  if (isLab) {
    const pricingLists = await Promise.all(
      approved.map((c) =>
        listClinicPricing(ctx.tenantId, c.clinicTenantId).then(
          (rows) => [c.clinicTenantId, rows] as const,
        ),
      ),
    );
    for (const [id, rows] of pricingLists) pricingByCounterpart.set(id, rows);
  } else {
    // Clinic side: only its own pricing rules from each lab, read-only
    const pricingLists = await Promise.all(
      approved.map((c) =>
        listClinicPricing(c.labTenantId, ctx.tenantId).then(
          (rows) => [c.labTenantId, rows] as const,
        ),
      ),
    );
    for (const [id, rows] of pricingLists) pricingByCounterpart.set(id, rows);
  }
  const pricingObject: Record<string, ClinicPricing[]> = Object.fromEntries(
    pricingByCounterpart,
  );
  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">Bağlantı Kur</h1>
        <p className="text-muted-foreground text-sm">
          {isLab
            ? "Sizinle çalışan klinikleri yönetin. Bağlantı kodunuzu paylaşın veya bir kliniğe talep gönderin."
            : "Çalıştığınız laboratuvarları yönetin. Bağlantı kodunuzu paylaşın veya bir laboratuvara talep gönderin."}
        </p>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <ConnectionCodeCard memberNumber={memberNumber} />
        <Card>
          <CardHeader>
            <CardTitle>Bağlantı talep et</CardTitle>
            <CardDescription>
              Karşı tarafın 6 haneli kodunu girin, onaylarsa bağlantı kurulur.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ConnectionRequestForm counterpartLabel={counterpartLabel} />
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 xl:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Gelen Talepler</CardTitle>
            <CardDescription>
              Size gönderilen, onayınızı bekleyen bağlantı talepleri.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <PendingInboundTable rows={pendingInbound} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Gönderilen Talepler</CardTitle>
            <CardDescription>
              Sizin gönderdiğiniz, karşı tarafın yanıtını bekleyen talepler.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <PendingOutboundTable rows={pendingOutbound} />
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Bağlantılarım</CardTitle>
          <CardDescription>
            Onaylanmış aktif bağlantılar.
            {isLab && " Lab tarafı her klinik için özel fiyat/indirim tanımlayabilir."}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <ConnectionsTable
            rows={approved}
            selfKind={ctx.kind}
            pricingByCounterpart={pricingObject}
            defaultCurrency={defaultCurrency}
          />
        </CardContent>
      </Card>
    </div>
  );
}
