"use client";

import { GlassContainer } from "@/components/ui/GlassContainer";
import { CodeBlock } from "../../components/CodeBlock";

interface TroubleshootingItem {
  problem: string;
  cause: string;
  solution: string;
  code?: string;
}

const commonIssues: TroubleshootingItem[] = [
  {
    problem: "\"Connection refused\" on localhost:4000",
    cause: "LLMHosts server is not running or bound to a different port/interface.",
    solution: "Start the server and verify the port:",
    code: `# Start the server
llmhosts serve

# Or check if something else is on port 4000
lsof -i :4000`,
  },
  {
    problem: "\"Model not found\" error",
    cause: "The requested model is not installed or not available on any connected backend.",
    solution: "Check available models with the doctor command, or restart the server to auto-provision:",
    code: `# Run diagnostics to see available models
llmhosts doctor

# Restart the server (auto-discovers and provisions models)
llmhosts serve

# Verify LLMHosts sees your models
curl http://localhost:4000/v1/models`,
  },
  {
    problem: "Slow inference / high latency",
    cause: "Model too large for GPU VRAM, falling back to CPU. Or router overhead from unused tiers.",
    solution: "Use a model that fits in VRAM, or disable unused router tiers:",
    code: `# Check VRAM usage
nvidia-smi

# Suggest models that fit your GPU
llmhosts suggest-models

# Disable Tier 3 if not needed (in config.toml)
# [router]
# tier3_enabled = false`,
  },
  {
    problem: "\"502 Bad Gateway\" errors",
    cause: "Inference engine crashed or is not responding. Common with OOM (out of memory) conditions.",
    solution: "Check engine status and restart if needed:",
    code: `# Run diagnostics to check backend health
llmhosts doctor

# Restart LLMHosts (automatically manages the inference engine)
llmhosts serve

# Check LLMHosts health
curl http://localhost:4000/health`,
  },
  {
    problem: "Tunnel not connecting",
    cause: "Tailscale or Cloudflare Tunnel not installed, not authenticated, or firewall blocking.",
    solution: "Verify tunnel provider is available:",
    code: `# Check Tailscale status
tailscale status

# Or check Cloudflare Tunnel
cloudflared tunnel list

# Run diagnostics
llmhosts doctor`,
  },
  {
    problem: "\"Unauthorized\" (401) on remote requests",
    cause: "Missing or invalid API key. Remote requests require authentication.",
    solution: "Generate and use an API key:",
    code: `# Generate a key
llmhosts keys add my-remote-key

# Use it in requests
curl https://your-tunnel-url/v1/models \\
  -H "Authorization: Bearer llmh_your_key_here"`,
  },
];

export default function TroubleshootingContent() {
  return (
    <div>
      <h1 className="text-4xl font-bold tracking-tight text-white">
        Troubleshooting
      </h1>
      <p className="mt-4 text-lg text-gray-400">
        Solutions for common LLMHosts issues, diagnostic interpretation, and
        performance tuning tips.
      </p>

      {/* Doctor Command */}
      <section className="mt-12">
        <h2 className="text-2xl font-semibold text-white mb-4">
          Using llmhosts doctor
        </h2>
        <p className="text-gray-400 mb-4">
          The{" "}
          <code className="rounded bg-white/[0.06] px-1.5 py-0.5 text-sm text-violet-400">
            llmhosts doctor
          </code>{" "}
          command runs a comprehensive diagnostic suite. Here is how to interpret
          the output:
        </p>
        <CodeBlock
          title="Example output"
          code={`$ llmhosts doctor

System Diagnostics
==================
[PASS] Python 3.12.1
[PASS] GPU detected: NVIDIA RTX 4090 (24GB VRAM)
[PASS] CUDA 12.4 available
[WARN] Only 2GB VRAM free (model may swap to CPU)

Backend Connectivity
====================
[PASS] Inference engine reachable at localhost:11434
[PASS] 3 models available: llama3.2, mistral:7b, codellama:13b
[FAIL] No cloud provider keys configured

Router Status
=============
[PASS] Tier 1 (kNN) initialized — 128 embeddings loaded
[PASS] Tier 2 (ModernBERT) loaded — ONNX runtime
[SKIP] Tier 3 (Qwen) disabled in config

Network
=======
[PASS] Tailscale connected — 100.x.x.x
[PASS] Tunnel accessible at https://gpu.llmhosts.com:4000

Key Storage
===========
[PASS] Fernet key initialized
[WARN] No API keys stored — add with: llmhosts keys add <provider> <key>`}
        />
        <div className="mt-6 overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-white/10">
                <th className="py-2 pr-4 text-left font-medium text-gray-300">
                  Status
                </th>
                <th className="py-2 text-left font-medium text-gray-300">
                  Meaning
                </th>
              </tr>
            </thead>
            <tbody className="text-gray-400">
              <tr className="border-b border-white/[0.06]">
                <td className="py-2 pr-4">
                  <span className="text-emerald-400 font-medium">[PASS]</span>
                </td>
                <td className="py-2">Component is working correctly</td>
              </tr>
              <tr className="border-b border-white/[0.06]">
                <td className="py-2 pr-4">
                  <span className="text-amber-400 font-medium">[WARN]</span>
                </td>
                <td className="py-2">
                  Working but may cause issues (e.g. low VRAM, missing optional config)
                </td>
              </tr>
              <tr className="border-b border-white/[0.06]">
                <td className="py-2 pr-4">
                  <span className="text-red-400 font-medium">[FAIL]</span>
                </td>
                <td className="py-2">
                  Component is broken or unavailable. Needs action.
                </td>
              </tr>
              <tr className="border-b border-white/[0.06]">
                <td className="py-2 pr-4">
                  <span className="text-gray-500 font-medium">[SKIP]</span>
                </td>
                <td className="py-2">
                  Component is disabled in configuration
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      {/* Common Issues */}
      <section className="mt-12">
        <h2 className="text-2xl font-semibold text-white mb-6">
          Common Issues
        </h2>
        <div className="space-y-8">
          {commonIssues.map((issue, idx) => (
            <GlassContainer key={idx} intensity="subtle" className="p-5">
              <h3 className="text-lg font-medium text-white mb-2">
                {issue.problem}
              </h3>
              <p className="text-sm text-gray-400 mb-1">
                <span className="font-medium text-gray-300">Cause:</span>{" "}
                {issue.cause}
              </p>
              <p className="text-sm text-gray-400 mb-3">
                <span className="font-medium text-gray-300">Solution:</span>{" "}
                {issue.solution}
              </p>
              {issue.code && <CodeBlock code={issue.code} language="bash" />}
            </GlassContainer>
          ))}
        </div>
      </section>

      {/* Performance Tuning */}
      <section className="mt-12">
        <h2 className="text-2xl font-semibold text-white mb-4">
          Performance Tuning
        </h2>
        <div className="space-y-6">
          <div>
            <h3 className="text-lg font-medium text-gray-200 mb-2">
              Maximize GPU utilization
            </h3>
            <ul className="list-disc list-inside space-y-1 text-sm text-gray-400">
              <li>
                Use quantized models (Q4_K_M) for larger context without
                exceeding VRAM
              </li>
              <li>
                Monitor with{" "}
                <code className="text-violet-400">nvidia-smi -l 1</code> during
                load testing
              </li>
              <li>
                Set{" "}
                <code className="text-violet-400">CUDA_VISIBLE_DEVICES</code>{" "}
                to pin specific GPUs
              </li>
            </ul>
          </div>

          <div>
            <h3 className="text-lg font-medium text-gray-200 mb-2">
              Reduce router latency
            </h3>
            <ul className="list-disc list-inside space-y-1 text-sm text-gray-400">
              <li>
                Raise{" "}
                <code className="text-violet-400">tier1_threshold</code> to
                resolve more queries at Tier 1 (&lt;15ms)
              </li>
              <li>
                Disable Tier 3 if you do not need LLM-based routing decisions
              </li>
              <li>
                Use{" "}
                <code className="text-violet-400">fallback_model</code> for a
                fast default when router is uncertain
              </li>
            </ul>
          </div>

          <div>
            <h3 className="text-lg font-medium text-gray-200 mb-2">
              Optimize cache hit rate
            </h3>
            <ul className="list-disc list-inside space-y-1 text-sm text-gray-400">
              <li>
                Lower{" "}
                <code className="text-violet-400">semantic_threshold</code> to
                0.85 for more cache hits (at the cost of occasional mismatches)
              </li>
              <li>
                Increase{" "}
                <code className="text-violet-400">max_size_mb</code> if you have
                available RAM
              </li>
              <li>
                Use LRU eviction for request patterns with temporal locality
              </li>
            </ul>
          </div>
        </div>
      </section>

      {/* Getting Help */}
      <section className="mt-12">
        <GlassContainer className="p-6">
          <h2 className="text-lg font-semibold text-white mb-3">
            Still stuck?
          </h2>
          <ul className="space-y-2 text-sm text-gray-400">
            <li>
              Run{" "}
              <code className="rounded bg-white/[0.06] px-1.5 py-0.5 text-xs text-violet-400">
                llmhosts doctor
              </code>{" "}
              and share the output in your support request
            </li>
            <li>
              Check the{" "}
              <code className="rounded bg-white/[0.06] px-1.5 py-0.5 text-xs text-gray-300">
                ~/.llmhosts/logs/
              </code>{" "}
              directory for detailed error logs
            </li>
            <li>
              Pro and Team customers can reach support directly from the
              dashboard
            </li>
          </ul>
        </GlassContainer>
      </section>
    </div>
  );
}
