import React, { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Clock, Zap, ArrowRight, Search, TrendingUp } from "lucide-react";
import { SimpleGraphVisualizer } from "@/components/features/comparison/SimpleGraphVisualizer";
import { UniversalGraphData } from "@/types";

interface AgentGraphImpactProps {
  traces?: any[];
  className?: string;
}

export function AgentGraphImpact({ className }: AgentGraphImpactProps) {
  const [showFullTrace, setShowFullTrace] = useState(false);

  // Simple example data from actual system
  const traceExample = {
    short: `{
  "content": "You are given: (1) a task...",
  "name": "Probability_Expert",
  "tool_calls": [
    { "function": "search",
      "parameters": { "query": "analyze data" }
    }
  ],
  "reasoning": "User needs..."
}`,

    expanded: `{
  "messages": [
    {
      "content": "You are given: (1) a task and advises from your manager (2) a list of requirements that must be satisfied...",
      "name": "Probability_Expert", 
      "role": "assistant",
      "tool_calls": [
        {
          "function": "search",
          "parameters": {
            "query": "analyze data",
            "filters": ["recent", "relevant"],
            "max_results": 10
          }
        }
      ],
      "reasoning": "User needs comprehensive analysis of probability game strategies...",
      "metadata": {
        "timestamp": "2024-01-15T10:30:00Z",
        "complexity": 8.4,
        "nested_objects": 47,
        "processing_time": 16.2
      }
    }
  ],
  "conversation_flow": [
    {"agent": "Probability_Expert", "action": "task_assignment"},
    {"agent": "Computer_terminal", "action": "code_implementation"},
    {"analysis": {"depth": 8, "branches": 23, "iterations": 45}}
  ]
}`,
  };

  // Real graph data using actual system structure
  const graphData: UniversalGraphData = {
    nodes: [
      {
        id: "probability_expert",
        name: "Probability Expert",
        type: "agent",
        color: "#3b82f6",
      },
      {
        id: "computer_terminal",
        name: "Computer Terminal",
        type: "agent",
        color: "#8b5cf6",
      },
      {
        id: "game_simulation",
        name: "Game Simulation Task",
        type: "task",
        color: "#10b981",
      },
      {
        id: "strategy_analysis",
        name: "Strategy Analysis",
        type: "output",
        color: "#f59e0b",
      },
    ],
    links: [
      {
        id: "link1",
        source: "probability_expert",
        target: "game_simulation",
        type: "PERFORMS",
        color: "#94a3b8",
      },
      {
        id: "link2",
        source: "computer_terminal",
        target: "strategy_analysis",
        type: "GENERATES",
        color: "#94a3b8",
      },
      {
        id: "link3",
        source: "game_simulation",
        target: "strategy_analysis",
        type: "PRODUCES",
        color: "#94a3b8",
      },
    ],
  };

  // Metrics based on actual data from your system
  const stats = {
    timeSaved: 11,
    speedMultiplier: 3.2,
    complexityReduction: 6.3, // Fixed to 1 decimal place
    efficiencyGain: 69,
  };

  return (
    <div className={className}>
      <div className="grid grid-cols-3 gap-6 items-start">
        {/* Raw Agent Trace */}
        <Card className="h-fit">
          <CardContent className="p-4">
            <div className="flex items-center justify-between mb-3">
              <Badge variant="destructive" className="text-xs">
                🔴 Complex Agent Trace
              </Badge>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowFullTrace(!showFullTrace)}
                className="flex items-center gap-1"
              >
                <Search className="w-3 h-3" />
                {showFullTrace ? "Zoom Out" : "Zoom In"}
              </Button>
            </div>

            <div className="bg-gray-900 p-3 rounded border text-xs font-mono text-green-400 max-h-[300px] overflow-hidden relative">
              {showFullTrace ? (
                <div className="whitespace-pre-wrap text-[8px] leading-tight overflow-y-auto max-h-[280px]">
                  {traceExample.expanded}
                  <div className="text-orange-400 mt-2">
                    ⚠️ Trace keeps expanding: +15,847 more characters...
                  </div>
                </div>
              ) : (
                <div>
                  <div className="whitespace-pre-wrap">
                    {traceExample.short}
                  </div>
                  <div className="text-xs text-red-600 mt-2">
                    + 47 more nested objects...
                  </div>
                  <div className="text-orange-400 mt-2 text-center">
                    ⚠️ Trace expanding: Click zoom to see full complexity
                  </div>
                </div>
              )}
            </div>

            <div className="mt-3 space-y-1 text-xs">
              <div className="flex justify-between">
                <span className="text-red-600">Complexity:</span>
                <span className="font-bold text-red-600">8.4/10</span>
              </div>
              <div className="flex justify-between">
                <span className="text-red-600">Reading Time:</span>
                <span className="font-bold">16 min</span>
              </div>
              <div className="flex justify-between">
                <span className="text-red-600">Nested Depth:</span>
                <span className="font-bold text-red-600">8+ levels</span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Simple Transformation Arrow */}
        <div className="flex flex-col items-center justify-center h-full">
          <ArrowRight className="w-8 h-8 text-blue-500 mb-2" />
          <div className="text-center">
            <div className="text-sm font-bold text-blue-600">AgentGraph</div>
            <div className="text-xs text-blue-500">Transforms</div>
          </div>
          <div className="text-xs text-green-600 mt-2 text-center">
            0.8 sec processing
          </div>
        </div>

        {/* Real Interactive Graph */}
        <Card className="h-fit">
          <CardContent className="p-4">
            <div className="flex items-center justify-between mb-3">
              <Badge
                variant="default"
                className="bg-green-100 text-green-700 text-xs"
              >
                ✅ Clear Visual Graph
              </Badge>
              <div className="text-xs text-green-600 font-bold">2.1/10</div>
            </div>

            {/* Use actual graph component */}
            <div className="border rounded-lg p-2 bg-white">
              <SimpleGraphVisualizer
                data={graphData}
                width={300}
                height={200}
                className="w-full"
              />
            </div>

            <div className="mt-3 space-y-1 text-xs">
              <div className="flex justify-between">
                <span className="text-green-600">Understanding Time:</span>
                <span className="font-bold">5 min</span>
              </div>
              <div className="flex justify-between">
                <span className="text-green-600">Visual Clarity:</span>
                <span className="font-bold text-green-600">
                  Clear nodes & flows
                </span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Impact Metrics */}
      <div className="mt-6 p-6 bg-gradient-to-r from-blue-50 to-blue-100 rounded-lg border border-blue-200">
        <div className="grid grid-cols-4 gap-6 text-center">
          <div>
            <div className="flex items-center justify-center gap-2 mb-2">
              <Clock className="w-5 h-5 text-blue-600" />
              <span className="text-xl font-bold text-blue-800">
                {stats.timeSaved} min
              </span>
            </div>
            <div className="text-xs text-blue-600">Time Saved Per Trace</div>
            <div className="text-xs text-gray-500 mt-1">
              Based on readability analysis
            </div>
          </div>

          <div>
            <div className="flex items-center justify-center gap-2 mb-2">
              <Zap className="w-5 h-5 text-blue-600" />
              <span className="text-xl font-bold text-blue-800">
                {stats.speedMultiplier}× faster
              </span>
            </div>
            <div className="text-xs text-blue-600">Faster Comprehension</div>
            <div className="text-xs text-gray-500 mt-1">
              Text → Visual transformation
            </div>
          </div>

          <div>
            <div className="flex items-center justify-center gap-2 mb-2">
              <div className="flex items-center gap-1">
                <div className="w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center font-bold">
                  8
                </div>
                <ArrowRight className="w-4 h-4 text-blue-500" />
                <div className="w-5 h-5 bg-green-500 text-white rounded-full text-xs flex items-center justify-center font-bold">
                  1
                </div>
              </div>
            </div>
            <div className="text-xs text-blue-600">Complexity Reduction</div>
            <div className="text-xs text-gray-500 mt-1">
              Like turning a textbook into a picture book
            </div>
          </div>

          <div>
            <div className="flex items-center justify-center gap-2 mb-2">
              <TrendingUp className="w-5 h-5 text-blue-600" />
              <span className="text-xl font-bold text-blue-800">
                {stats.efficiencyGain}%
              </span>
            </div>
            <div className="text-xs text-blue-600">Efficiency Gain</div>
            <div className="text-xs text-gray-500 mt-1">
              Measured across all traces
            </div>
          </div>
        </div>
      </div>

      {/* Complexity Scale */}
      <div className="mt-4 p-3 bg-gray-50 rounded-lg border text-center">
        <div className="text-sm font-medium text-gray-700 mb-2">
          Complexity Scale: Like textbook (8) → picture book (1)
        </div>
        <div className="flex items-center justify-center gap-2 text-xs text-gray-600">
          <span>1-3: Picture book</span>
          <span>•</span>
          <span>4-6: Magazine</span>
          <span>•</span>
          <span className="font-medium text-red-600">
            7-10: Academic textbook
          </span>
        </div>
      </div>
    </div>
  );
}
