"use client";

import { AGENT_TOOL_PREFIX, isAgentTool, parseFullToolName } from "@shared";
import { formatDistanceToNow } from "date-fns";
import {
  ChevronDown,
  ChevronRight,
  Layers,
  Sparkles,
  User,
} from "lucide-react";
import { useState } from "react";
import { TruncatedText } from "@/components/truncated-text";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { useInternalMcpCatalog } from "@/lib/mcp/internal-mcp-catalog.query";
import type { ToolWithAssignmentsData } from "@/lib/tools/tool.query";
import { isMcpToolByProperties } from "@/lib/tools/tool.utils";
import { formatDate } from "@/lib/utils";
import { ToolCallPolicies } from "./tool-call-policies";
import { ToolReadonlyDetails } from "./tool-readonly-details";
import { ToolResultPolicies } from "./tool-result-policies";

interface ToolDetailsDialogProps {
  tool: ToolWithAssignmentsData | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function ToolDetailsDialog({
  tool,
  open,
  onOpenChange,
}: ToolDetailsDialogProps) {
  const { data: internalMcpCatalogItems } = useInternalMcpCatalog();
  const [assignmentsOpen, setAssignmentsOpen] = useState(true);

  if (!tool) return null;

  // Only trim prefix for MCP tools (which have catalogId set and were slugified with server name)
  // LLM proxy discovered tools (no catalogId) should show the full name as-is
  const displayName = tool.catalogId
    ? parseFullToolName(tool.name).toolName || tool.name
    : tool.name;

  const catalogItem = internalMcpCatalogItems?.find(
    (item) => item.id === tool.catalogId,
  );

  // Check if this is a built-in Archestra tool (no credentials required)
  // Helper to get credential display text
  // Backend returns null for emails when user doesn't have access to the credential's MCP server
  // Returns null when there's no credential to display
  const getCredentialDisplay = (
    assignment: (typeof tool.assignments)[0],
  ): string | null => {
    if (assignment.credentialResolutionMode === "dynamic") {
      return "Resolve at call time";
    }

    if (!assignment.mcpServerId) {
      return null;
    }

    // Backend returns email if user has access, null if not
    const email =
      assignment.credentialOwnerEmail || assignment.executionOwnerEmail;

    if (!email) {
      // Credential server exists but user doesn't have access
      return "Owner outside your team";
    }

    return email;
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-5xl h-[90vh] flex flex-col overflow-hidden">
        <DialogHeader className="sticky top-0 z-10 shrink-0 bg-background">
          <div className="flex items-start justify-between">
            <div className="flex-1 min-w-0">
              {tool.description ? (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <DialogTitle className="text-xl font-semibold tracking-tight truncate cursor-help">
                        {displayName}
                      </DialogTitle>
                    </TooltipTrigger>
                    <TooltipContent
                      side="bottom"
                      align="start"
                      className="max-w-md"
                    >
                      <p>{tool.description}</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              ) : (
                <DialogTitle className="text-xl font-semibold tracking-tight truncate">
                  {displayName}
                </DialogTitle>
              )}
              {tool.description && (
                <TruncatedText
                  message={tool.description}
                  maxLength={200}
                  className="text-sm text-muted-foreground mt-1"
                />
              )}
            </div>
            <div className="flex gap-6 text-sm ml-6">
              <div>
                <div className="text-xs font-medium text-muted-foreground">
                  Origin
                </div>
                <div className="mt-0.5">
                  {isMcpToolByProperties(tool) ? (
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Badge variant="default" className="bg-indigo-500">
                            MCP Server
                          </Badge>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>{catalogItem?.name || "MCP Server"}</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  ) : isAgentTool(tool.name) ? (
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Badge
                            variant="secondary"
                            className="bg-violet-600 text-white"
                          >
                            Agent
                          </Badge>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>
                            Delegates to{" "}
                            {tool.name
                              .slice(AGENT_TOOL_PREFIX.length)
                              .replaceAll("_", " ")}{" "}
                            agent
                          </p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  ) : (
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Badge variant="secondary" className="bg-orange-800">
                            Intercepted
                          </Badge>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>Tool discovered via agent-LLM communication</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  )}
                </div>
              </div>
              <div>
                <div className="text-xs font-medium text-muted-foreground">
                  Detected
                </div>
                <div className="text-sm text-foreground mt-0.5">
                  {formatDate({ date: tool.createdAt })}
                </div>
              </div>
              <div>
                <div className="text-xs font-medium text-muted-foreground">
                  Updated
                </div>
                <div className="text-sm text-foreground mt-0.5">
                  {formatDate({ date: tool.updatedAt })}
                </div>
              </div>
            </div>
          </div>
        </DialogHeader>

        <DialogBody className="space-y-4">
          {tool.policiesAutoConfiguredReasoning && (
            <div className="flex items-start gap-3 rounded-lg border border-border bg-card p-4">
              <Sparkles className="h-4 w-4 mt-0.5 shrink-0 text-purple-400" />
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium">
                    AI Policy Reasoning
                  </span>
                  {tool.policiesAutoConfiguredAt && (
                    <span className="text-xs text-muted-foreground">
                      {formatDistanceToNow(
                        new Date(tool.policiesAutoConfiguredAt),
                        { addSuffix: true },
                      )}
                      {tool.policiesAutoConfiguredModel &&
                        ` with ${tool.policiesAutoConfiguredModel}`}
                    </span>
                  )}
                </div>
                <p className="text-sm text-muted-foreground mt-1">
                  {tool.policiesAutoConfiguredReasoning}
                </p>
              </div>
            </div>
          )}

          <ToolReadonlyDetails tool={tool} />

          {/* Assignments Section */}
          <Collapsible open={assignmentsOpen} onOpenChange={setAssignmentsOpen}>
            <div className="border border-border rounded-lg bg-card">
              <CollapsibleTrigger asChild>
                <Button
                  variant="ghost"
                  className="w-full flex items-center justify-between p-4 hover:bg-muted/50 rounded-t-lg"
                >
                  <div className="flex items-center gap-2">
                    <User className="h-4 w-4" />
                    <span className="font-semibold text-sm">
                      Assignments to Agents and MCP Gateways
                    </span>
                    <Badge variant="secondary" className="ml-2">
                      {tool.assignmentCount}
                    </Badge>
                  </div>
                  {assignmentsOpen ? (
                    <ChevronDown className="h-4 w-4" />
                  ) : (
                    <ChevronRight className="h-4 w-4" />
                  )}
                </Button>
              </CollapsibleTrigger>
              <CollapsibleContent>
                <div className="border-t border-border">
                  {tool.assignments.length === 0 ? (
                    <div className="p-4 text-sm text-muted-foreground text-center">
                      Not assigned to agent or MCP gateway.
                    </div>
                  ) : (
                    <div className="divide-y divide-border">
                      {tool.assignments.map((assignment) => {
                        const credentialDisplay =
                          getCredentialDisplay(assignment);
                        return (
                          <div
                            key={assignment.agentToolId}
                            className="p-4 space-y-3"
                          >
                            <div className="flex items-center justify-between">
                              <div className="flex items-center gap-3">
                                <Badge variant="secondary" className="gap-1">
                                  <Layers className="h-3 w-3" />
                                  {assignment.agent.name}
                                </Badge>
                                {credentialDisplay && (
                                  <>
                                    <span className="text-muted-foreground">
                                      →
                                    </span>
                                    <span className="text-sm text-muted-foreground">
                                      {credentialDisplay}
                                    </span>
                                  </>
                                )}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              </CollapsibleContent>
            </div>
          </Collapsible>

          <ToolResultPolicies tool={tool} />
          <ToolCallPolicies tool={tool} />
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
}
