import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';

type OSTab = 'macos' | 'linux' | 'windows';

const INSTALL_COMMANDS = {
  macos: {
    install: 'pip install pulse-os',
    init: 'pulse init',
    python: 'python3 --version  # Requires Python 3.9+',
    pip: 'pip3 --version',
  },
  linux: {
    install: 'pip install pulse-os',
    init: 'pulse init',
    python: 'python3 --version  # Requires Python 3.9+',
    pip: 'pip3 --version',
  },
  windows: {
    install: 'pip install pulse-os',
    init: 'pulse init',
    python: 'python --version  # Requires Python 3.9+',
    pip: 'pip --version',
  },
};

function AnimatedTerminal({ command, delay = 0 }: { command: string; delay?: number }) {
  const [displayedText, setDisplayedText] = useState('');
  const [cursorVisible, setCursorVisible] = useState(true);

  useEffect(() => {
    let timeout: ReturnType<typeof setTimeout>;
    let currentIndex = 0;

    const typeText = () => {
      if (currentIndex < command.length) {
        setDisplayedText(command.slice(0, currentIndex + 1));
        currentIndex++;
        timeout = setTimeout(typeText, 50 + Math.random() * 50);
      }
    };

    timeout = setTimeout(() => {
      typeText();
    }, delay);

    return () => clearTimeout(timeout);
  }, [command, delay]);

  useEffect(() => {
    const interval = setInterval(() => {
      setCursorVisible((v) => !v);
    }, 530);
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="font-mono text-sm sm:text-base text-green-400">
      <span className="text-sky-400">$</span> {displayedText}
      {displayedText.length < command.length && (
        <span className={`inline-block w-2 h-4 ml-1 bg-green-400 ${cursorVisible ? 'opacity-100' : 'opacity-0'}`} />
      )}
    </div>
  );
}

function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <button
      onClick={handleCopy}
      className="px-3 py-1.5 rounded-lg bg-slate-700/50 border border-slate-600/50 text-slate-300 text-xs font-medium hover:bg-slate-600/50 hover:border-sky-400/50 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950"
      aria-label={copied ? 'Copied!' : 'Copy to clipboard'}
    >
      {copied ? '✓ Copied' : 'Copy'}
    </button>
  );
}

function CodeBlock({ code, showCopy = true }: { code: string; showCopy?: boolean }) {
  return (
    <div className="relative group">
      <pre className="bg-slate-900/90 border border-slate-700/50 rounded-xl p-4 overflow-x-auto text-sm font-mono text-slate-300">
        {code}
      </pre>
      {showCopy && (
        <div className="absolute top-3 right-3">
          <CopyButton text={code} />
        </div>
      )}
    </div>
  );
}

export default function Install() {
  const [selectedOS, setSelectedOS] = useState<OSTab>('macos');

  const commands = INSTALL_COMMANDS[selectedOS];

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      {/* Header */}
      <div className="border-b border-slate-800/50 bg-slate-900/50 backdrop-blur-sm sticky top-0 z-10">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <h1 className="text-3xl sm:text-4xl font-bold text-sky-400">Installation Guide</h1>
          <p className="text-slate-400 mt-2">Get PULSE running in under 5 minutes</p>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Prerequisites Section */}
        <motion.section
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="mb-16"
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-6">Prerequisites</h2>
          <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
            <ul className="space-y-4">
              <li className="flex items-start gap-3">
                <span className="text-green-400 text-xl flex-shrink-0">✓</span>
                <div>
                  <strong className="text-slate-200">Python 3.9+</strong>
                  <p className="text-slate-400 text-sm mt-1">
                    PULSE requires Python 3.9 or higher. Check your version with <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">python --version</code>
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <span className="text-green-400 text-xl flex-shrink-0">✓</span>
                <div>
                  <strong className="text-slate-200">pip</strong>
                  <p className="text-slate-400 text-sm mt-1">
                    Python package installer (usually bundled with Python). Verify with <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">pip --version</code>
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <span className="text-green-400 text-xl flex-shrink-0">✓</span>
                <div>
                  <strong className="text-slate-200">Git</strong>
                  <p className="text-slate-400 text-sm mt-1">
                    Required for version control and brain history. Get it from <a href="https://git-scm.com" target="_blank" rel="noopener noreferrer" className="text-sky-400 hover:underline">git-scm.com</a>
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <span className="text-sky-400 text-xl flex-shrink-0">○</span>
                <div>
                  <strong className="text-slate-200">API Keys (Optional)</strong>
                  <p className="text-slate-400 text-sm mt-1">
                    For agent functionality: <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">ANTHROPIC_API_KEY</code>, <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">GOOGLE_API_KEY</code>, <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">OPENAI_API_KEY</code>
                  </p>
                </div>
              </li>
            </ul>
          </div>
        </motion.section>

        {/* OS Tabs */}
        <motion.section
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="mb-16"
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-6">Quick Start</h2>

          {/* Tab Buttons */}
          <div className="flex gap-2 mb-6 bg-slate-800/30 backdrop-blur-sm border border-slate-700/50 rounded-xl p-2 w-fit">
            {(['macos', 'linux', 'windows'] as OSTab[]).map((os) => (
              <button
                key={os}
                onClick={() => setSelectedOS(os)}
                className={`px-6 py-2.5 rounded-lg font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950 ${
                  selectedOS === os
                    ? 'bg-sky-500 text-slate-950'
                    : 'text-slate-400 hover:text-slate-200 hover:bg-slate-700/50'
                }`}
              >
                {os === 'macos' ? 'macOS' : os === 'linux' ? 'Linux' : 'Windows'}
              </button>
            ))}
          </div>

          {/* Animated Terminal */}
          <div className="bg-slate-900/90 backdrop-blur-sm border border-slate-700/50 rounded-2xl overflow-hidden">
            {/* Terminal Header */}
            <div className="bg-slate-800/80 border-b border-slate-700/50 px-4 py-3 flex items-center gap-2">
              <div className="flex gap-2">
                <div className="w-3 h-3 rounded-full bg-red-500/80" />
                <div className="w-3 h-3 rounded-full bg-yellow-500/80" />
                <div className="w-3 h-3 rounded-full bg-green-500/80" />
              </div>
              <span className="ml-4 text-slate-400 text-sm font-medium">terminal</span>
            </div>

            {/* Terminal Content */}
            <div className="p-6 space-y-4">
              <AnimatedTerminal command={commands.install} delay={500} />
              <AnimatedTerminal command={commands.init} delay={3000} />
            </div>
          </div>
        </motion.section>

        {/* Step-by-Step Instructions */}
        <motion.section
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
          className="mb-16"
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-6">Detailed Steps</h2>

          <div className="space-y-8">
            {/* Step 1 */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                  1
                </div>
                <div className="flex-1">
                  <h3 className="text-xl font-semibold text-slate-200 mb-3">Verify Prerequisites</h3>
                  <p className="text-slate-400 mb-4">Check that Python and pip are installed:</p>
                  <CodeBlock code={`${commands.python}\n${commands.pip}`} />
                </div>
              </div>
            </div>

            {/* Step 2 */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                  2
                </div>
                <div className="flex-1">
                  <h3 className="text-xl font-semibold text-slate-200 mb-3">Install PULSE</h3>
                  <p className="text-slate-400 mb-4">Run the pip install command:</p>
                  <CodeBlock code={commands.install} />
                  <p className="text-slate-400 text-sm mt-4">
                    This installs the <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">pulse</code> CLI and all dependencies.
                  </p>
                </div>
              </div>
            </div>

            {/* Step 3 */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                  3
                </div>
                <div className="flex-1">
                  <h3 className="text-xl font-semibold text-slate-200 mb-3">Initialize Your Brain</h3>
                  <p className="text-slate-400 mb-4">Create the PULSE directory structure:</p>
                  <CodeBlock code={commands.init} />
                  <p className="text-slate-400 text-sm mt-4">
                    This creates <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">~/.pulse/brain/</code> with Hippocampus regions, Corpus Callosum governance, and configuration files.
                  </p>
                </div>
              </div>
            </div>

            {/* Step 4 */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-10 h-10 rounded-full bg-sky-500/20 border border-sky-400/50 flex items-center justify-center text-sky-400 font-bold">
                  4
                </div>
                <div className="flex-1">
                  <h3 className="text-xl font-semibold text-slate-200 mb-3">Configure API Keys (Optional)</h3>
                  <p className="text-slate-400 mb-4">Set environment variables for agent providers:</p>
                  <CodeBlock
                    code={selectedOS === 'windows'
                      ? 'set ANTHROPIC_API_KEY=sk-ant-...\nset GOOGLE_API_KEY=...\nset OPENAI_API_KEY=sk-...'
                      : 'export ANTHROPIC_API_KEY=sk-ant-...\nexport GOOGLE_API_KEY=...\nexport OPENAI_API_KEY=sk-...'}
                  />
                  <p className="text-slate-400 text-sm mt-4">
                    Or add them to <code className="px-2 py-0.5 rounded bg-slate-900/80 text-sky-300">~/.pulse/.env</code> for persistence.
                  </p>
                </div>
              </div>
            </div>

            {/* Step 5 */}
            <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 w-10 h-10 rounded-full bg-green-500/20 border border-green-400/50 flex items-center justify-center text-green-400 font-bold">
                  ✓
                </div>
                <div className="flex-1">
                  <h3 className="text-xl font-semibold text-slate-200 mb-3">Verify Installation</h3>
                  <p className="text-slate-400 mb-4">Check that PULSE is working:</p>
                  <CodeBlock code="pulse status" />
                  <p className="text-slate-400 text-sm mt-4">
                    You should see orchestrator status, brain health, and available agents.
                  </p>
                </div>
              </div>
            </div>
          </div>
        </motion.section>

        {/* Next Steps */}
        <motion.section
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.3 }}
        >
          <h2 className="text-2xl font-bold text-sky-400 mb-6">Next Steps</h2>
          <div className="bg-gradient-to-br from-sky-500/10 to-cyan-500/10 backdrop-blur-sm border border-sky-400/30 rounded-2xl p-8">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <a
                href="/dashboard"
                className="block p-6 rounded-xl bg-slate-800/50 border border-slate-700/50 hover:border-sky-400/50 transition-all duration-200 group"
              >
                <h3 className="text-lg font-semibold text-sky-400 mb-2 group-hover:text-sky-300">
                  Launch Dashboard →
                </h3>
                <p className="text-slate-400 text-sm">
                  Monitor agents, view brain stats, and manage your swarm
                </p>
              </a>

              <a
                href="/docs"
                className="block p-6 rounded-xl bg-slate-800/50 border border-slate-700/50 hover:border-sky-400/50 transition-all duration-200 group"
              >
                <h3 className="text-lg font-semibold text-sky-400 mb-2 group-hover:text-sky-300">
                  Read Documentation →
                </h3>
                <p className="text-slate-400 text-sm">
                  Learn about the brain pipeline, ASOP protocol, and Constitutional laws
                </p>
              </a>

              <a
                href="https://github.com/Honesty0x/PULSE"
                target="_blank"
                rel="noopener noreferrer"
                className="block p-6 rounded-xl bg-slate-800/50 border border-slate-700/50 hover:border-sky-400/50 transition-all duration-200 group"
              >
                <h3 className="text-lg font-semibold text-sky-400 mb-2 group-hover:text-sky-300">
                  View on GitHub →
                </h3>
                <p className="text-slate-400 text-sm">
                  Star the repo, report issues, or contribute to the project
                </p>
              </a>

              <div className="p-6 rounded-xl bg-slate-800/50 border border-slate-700/50">
                <h3 className="text-lg font-semibold text-sky-400 mb-2">
                  Need Help?
                </h3>
                <p className="text-slate-400 text-sm">
                  Join our community or check the FAQ for common questions
                </p>
              </div>
            </div>
          </div>
        </motion.section>
      </div>
    </div>
  );
}
