import React, { useState } from 'react';
import {
  Sparkles,
  XCircle,
  Code2,
  Copy,
  Check,
  Zap,
  Repeat,
  Compass,
  Layers,
  ArrowRight,
} from 'lucide-react';

interface MCPSkillGuideModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSendToStudio: (prompt: string) => void;
}

export const MCPSkillGuideModal: React.FC<MCPSkillGuideModalProps> = ({
  isOpen,
  onClose,
  onSendToStudio,
}) => {
  const [copiedSkillId, setCopiedSkillId] = useState<string | null>(null);

  if (!isOpen) return null;

  const handleCopy = (id: string, text: string) => {
    navigator.clipboard.writeText(text);
    setCopiedSkillId(id);
    setTimeout(() => setCopiedSkillId(null), 2000);
  };

  const skills = [
    {
      id: 'skill-autonomous-loop',
      title: 'Autonomous Self-Evaluating Feedback Loop Skill',
      icon: <Repeat className="w-5 h-5 text-indigo-400" />,
      tag: 'Autonomous Loops',
      tagColor: 'bg-indigo-900/60 text-indigo-300 border-indigo-700/50',
      description:
        'Pattern for creating MCP tools that execute recursive evaluation cycles, verify their own assertions, calculate confidence scores, and return self-correcting telemetry back to the AI model.',
      promptExample:
        'Create an autonomous loop MCP tool for code optimization that takes source code, benchmarks complexity, runs automated invariant checks, and suggests verified refactor steps with confidence scoring.',
      codeSnippet: `// Autonomous self-verifying feedback loop pattern
const { sourceCode, testAssertions } = args;
// 1. Execute transformation
const transformed = optimizeAst(sourceCode);
// 2. Self-verify invariants against test suite
const passRate = runVerificationChecks(transformed, testAssertions);
// 3. Output verifiable loop metrics
return {
  status: passRate === 1.0 ? 'converged' : 'needs_iteration',
  confidenceScore: passRate,
  optimizedCode: transformed,
  telemetry: { loopIterations: 1, memorySavedPercent: 24.5 }
};`,
    },
    {
      id: 'skill-zero-api-key',
      title: 'Zero-API-Key Pure Algorithmic Engine Skill',
      icon: <Zap className="w-5 h-5 text-emerald-400" />,
      tag: 'Pure Computation',
      tagColor: 'bg-emerald-900/60 text-emerald-300 border-emerald-700/50',
      description:
        'Construct lightning-fast tools that operate entirely in local JS/TS without relying on paid external APIs. Ideal for AST parsing, regex validation, math engines, SVG generation, and network CIDR calculations.',
      promptExample:
        'Build a zero-key SVG chart generator tool that takes an array of numbers and chart type (sparkline, gauge, bar) and returns production-ready scalable SVG strings and data URIs.',
      codeSnippet: `// Pure zero-API computation pattern
const numbers = args.values || [];
const max = Math.max(...numbers);
const min = Math.min(...numbers);
const points = numbers.map((n, i) => \`\${i * 20},\${100 - ((n - min) / (max - min)) * 80}\`).join(' ');
const svg = \`<svg viewBox="0 0 200 100"><polyline points="\${points}" stroke="#4f46e5" fill="none"/></svg>\`;
return { svg, dataUri: 'data:image/svg+xml;utf8,' + encodeURIComponent(svg) };`,
    },
    {
      id: 'skill-roadsign-bridge',
      title: 'Remote Host "Road Sign" Signpost Skill',
      icon: <Compass className="w-5 h-5 text-amber-400" />,
      tag: 'Remote Bridge & Credentials',
      tagColor: 'bg-amber-900/60 text-amber-300 border-amber-700/50',
      description:
        'Bridge remote desktop machines (e.g. Windows Workstation PowerShell, macOS shell, GPU clusters) by erecting an authoritative Road Sign on the Nexus with auto-injected Bearer tokens and API keys.',
      promptExample:
        'Set up a Windows Workstation MCP Road Sign pointing to http://192.168.1.150:8000/mcp with Bearer token authentication to expose local PowerShell execution and desktop window controls.',
      codeSnippet: `// Road sign configuration with injected credentials
{
  isRoadSign: true,
  signpostTitle: 'LOOK HERE: Windows Workstation Desktop MCP',
  targetHostLocation: 'http://192.168.1.150:8000/mcp',
  directionsInstructions: 'Access local Windows tools with auto-injected Bearer token',
  credentialKeys: {
    'Authorization': 'Bearer win_mcp_sec_9941a8',
    'X-Client-Origin': 'DoEverythingMCP-Nexus'
  }
}`,
    },
  ];

  return (
    <div className="fixed inset-0 z-50 bg-slate-900/70 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto">
      <div className="bg-white rounded-3xl max-w-3xl w-full p-6 sm:p-8 space-y-6 shadow-2xl border border-slate-200 my-8">
        <div className="flex items-start justify-between border-b border-slate-100 pb-5">
          <div className="flex items-center space-x-3">
            <div className="w-12 h-12 rounded-2xl bg-indigo-600 text-white flex items-center justify-center shadow-md">
              <Sparkles className="w-6 h-6" />
            </div>
            <div>
              <div className="flex items-center space-x-2">
                <span className="px-2 py-0.5 rounded text-[10px] font-black uppercase tracking-wider bg-indigo-100 text-indigo-800 border border-indigo-200">
                  CREATION SKILL GUIDE
                </span>
                <span className="text-xs text-slate-500 font-medium">Original MCP Architectures</span>
              </div>
              <h3 className="text-xl font-black text-slate-900 mt-0.5">
                The MCP Creation Skill & Design Principles
              </h3>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-xl transition"
          >
            <XCircle className="w-6 h-6" />
          </button>
        </div>

        <p className="text-xs sm:text-sm text-slate-600 leading-relaxed">
          Master the three foundational skills of original MCP construction: creating productive autonomous feedback loops, crafting zero-dependency algorithmic tools, and erecting secure remote host Road Signs.
        </p>

        <div className="space-y-4 max-h-[60vh] overflow-y-auto pr-1">
          {skills.map((skill) => (
            <div
              key={skill.id}
              className="bg-slate-900 text-white rounded-2xl p-5 border border-slate-800 space-y-4 shadow-md"
            >
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-slate-800 pb-3">
                <div className="flex items-center space-x-2.5">
                  <div className="p-2 rounded-xl bg-slate-800 border border-slate-700">
                    {skill.icon}
                  </div>
                  <div>
                    <h4 className="font-bold text-sm text-slate-100">{skill.title}</h4>
                    <span className={`inline-block px-2 py-0.5 rounded text-[10px] font-bold border mt-0.5 ${skill.tagColor}`}>
                      {skill.tag}
                    </span>
                  </div>
                </div>

                <button
                  type="button"
                  onClick={() => {
                    onSendToStudio(skill.promptExample);
                    onClose();
                  }}
                  className="px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold flex items-center space-x-1.5 self-start sm:self-center transition shadow-xs"
                >
                  <span>Build with AI Studio</span>
                  <ArrowRight className="w-3.5 h-3.5" />
                </button>
              </div>

              <p className="text-xs text-slate-300 leading-relaxed">{skill.description}</p>

              <div>
                <div className="flex items-center justify-between text-[11px] font-semibold text-slate-400 mb-1.5">
                  <span>Architecture Code Template:</span>
                  <button
                    type="button"
                    onClick={() => handleCopy(skill.id, skill.codeSnippet)}
                    className="text-indigo-400 hover:text-indigo-300 flex items-center space-x-1"
                  >
                    {copiedSkillId === skill.id ? <Check className="w-3.5 h-3.5 text-emerald-400" /> : <Copy className="w-3.5 h-3.5" />}
                    <span>{copiedSkillId === skill.id ? 'Copied!' : 'Copy Code'}</span>
                  </button>
                </div>
                <pre className="p-3 bg-slate-950 text-indigo-300 font-mono text-[11px] rounded-xl overflow-x-auto border border-slate-800/80">
                  {skill.codeSnippet}
                </pre>
              </div>
            </div>
          ))}
        </div>

        <div className="flex items-center justify-end pt-2 border-t border-slate-100">
          <button
            type="button"
            onClick={onClose}
            className="px-5 py-2.5 bg-slate-900 text-white font-bold rounded-xl hover:bg-slate-800 transition text-xs"
          >
            Close Guide
          </button>
        </div>
      </div>
    </div>
  );
};
