"use client";

import React from "react";
import MainTitle from "@/components/layout/dashboard/main-title";
// import ClientTenantBar from "./client-tenant-bar";
import {
  useTenantClientWorkspace,
  type WorkspaceMe,
} from "./use-tenant-client-workspace";

export type ClientWorkspaceChildCtx = {
  effectiveClientKey: string;
  /** Use with `tenantApiPath()` — `"me"` for tenant users, real client id for super admin. */
  tenantApiKey: string;
  tenantReady: boolean;
  me: WorkspaceMe;
  isSuperAdmin: boolean;
  /** Public API client key (e.g. slug). */
  tenantClientId: string | undefined;
  /** MongoDB Client document id for this workspace — compare to role.client for org roles. */
  workspaceClientDbId: string | undefined;
  moduleBlockedProperty: boolean;
};

type Props = {
  title: string;
  actions?: React.ReactNode | ((ctx: ClientWorkspaceChildCtx) => React.ReactNode);
  barDescription?: string;
  children: (ctx: ClientWorkspaceChildCtx) => React.ReactNode;
};

export default function ClientWorkspaceLayout({
  title,
  actions,
  // barDescription,
  children,
}: Props) {
  const ws = useTenantClientWorkspace();

  if (ws.loading || !ws.me) {
    return (
      <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>
    );
  }

  if (!ws.isSuperAdmin && !ws.tenantClientId) {
    return (
      <div>
        <MainTitle title={title} />
        <p className="rounded-md border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
          Your account is not linked to an API client (tenant). Ask a super admin to assign you to a
          client.
        </p>
      </div>
    );
  }

  if (ws.isSuperAdmin && ws.adminClients.length === 0) {
    return (
      <div>
        <MainTitle title={title} />
        <p className="text-sm text-gray-600">
          No API clients exist yet. Create one under{" "}
          <span className="font-medium">Super admin → Clients</span>, then return here.
        </p>
      </div>
    );
  }

  const ctx: ClientWorkspaceChildCtx = {
    effectiveClientKey: ws.effectiveClientKey,
    tenantApiKey: ws.tenantApiKey,
    tenantReady: ws.tenantReady,
    me: ws.me,
    isSuperAdmin: ws.isSuperAdmin,
    tenantClientId: ws.tenantClientId,
    workspaceClientDbId: ws.workspaceClientDbId,
    moduleBlockedProperty: ws.moduleBlockedProperty,
  };

  const actionsNode =
    typeof actions === "function" ? actions(ctx) : actions;

  return (
    <div className="min-w-0 space-y-4">
      <MainTitle title={title}>{actionsNode}</MainTitle>
      {/* <ClientTenantBar
        me={ws.me}
        isSuperAdmin={ws.isSuperAdmin}
        adminClients={ws.adminClients}
        selectedClientKey={ws.selectedClientKey}
        onClientChange={ws.setSelectedClientKey}
        description={barDescription}
      /> */}
      {children(ctx)}
    </div>
  );
}
