"use client";

import * as React from "react";
import { Bot } from "lucide-react";

import { sessionAllowsRouteKeys } from "@/app/customer/_lib/customer-route-guard";
import { PortfolioAgentPanel } from "@/components/sidebar/portfolio-agent/portfolio-agent-panel";
import { Button } from "@/components/ui/button";
import { CUSTOMER_ROUTE_KEYS } from "@/config/customer-route-keys";

type PortfolioAgentDialogProps = {
  tenant: string;
  allowedRoutes?: readonly string[];
};

/** Global Portfolio Agent — ⌘⇧K (beside Holdings ⌘⇧J). */
export function PortfolioAgentDialog({
  tenant,
  allowedRoutes,
}: PortfolioAgentDialogProps) {
  const [open, setOpen] = React.useState(false);

  const allowed = React.useMemo(() => {
    if (!allowedRoutes) return false;
    return sessionAllowsRouteKeys(allowedRoutes, [CUSTOMER_ROUTE_KEYS.portfolioAgentAsk]);
  }, [allowedRoutes]);

  React.useEffect(() => {
    if (!allowed) return;
    const down = (e: KeyboardEvent) => {
      if (e.key?.toLowerCase() === "k" && (e.metaKey || e.ctrlKey) && e.shiftKey) {
        e.preventDefault();
        setOpen((prev) => !prev);
      }
    };
    document.addEventListener("keydown", down);
    return () => document.removeEventListener("keydown", down);
  }, [allowed]);

  if (!allowed) return null;

  return (
    <>
      <Button
        onClick={() => setOpen(true)}
        variant="link"
        className="px-0! font-normal text-muted-foreground hover:no-underline"
        data-tutorial="portfolio-agent"
      >
        <Bot data-icon="inline-start" />
        Agent
        <kbd className="inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-medium text-[10px]">
          <span className="text-xs">⌘⇧</span>K
        </kbd>
      </Button>
      <PortfolioAgentPanel tenant={tenant} open={open} onOpenChange={setOpen} />
    </>
  );
}
