import { useState } from "react";
import PublicLayout from "@/components/PublicLayout";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Book, Key, Phone, BarChart3, Webhook, TestTube } from "lucide-react";

export default function Docs() {
  const [activeSection, setActiveSection] = useState("quick-start");

  const sections = [
    { id: "quick-start", title: "Quick Start", icon: Book },
    { id: "authentication", title: "Authentication", icon: Key },
    { id: "calls-api", title: "Calls API", icon: Phone },
    { id: "analytics", title: "Analytics", icon: BarChart3 },
    { id: "webhooks", title: "Webhooks", icon: Webhook },
    { id: "testing", title: "Testing Portal", icon: TestTube }
  ];

  const content = {
    "quick-start": {
      title: "Quick Start Guide",
      sections: [
        {
          title: "1. Create an Account",
          content: "Sign up for a Zyvra account and choose your plan. You'll get a 14-day free trial to test all features."
        },
        {
          title: "2. Get API Keys",
          content: "Navigate to Settings → API Keys and generate your first API key. Keep this secure as it's used to authenticate all API requests."
        },
        {
          title: "3. Make Your First Call",
          content: `Use our REST API to initiate a call:

curl -X POST https://api.zyvra.io/v1/calls \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "scenario": "banking",
    "customer_phone": "+1234567890"
  }'`
        }
      ]
    },
    "authentication": {
      title: "Authentication",
      sections: [
        {
          title: "API Key Authentication",
          content: "All API requests require an API key passed in the Authorization header as a Bearer token."
        },
        {
          title: "Example Request",
          content: `curl -H "Authorization: Bearer sk_live_..." \\
  https://api.zyvra.io/v1/calls`
        },
        {
          title: "Security Best Practices",
          content: "• Never commit API keys to version control\n• Rotate keys regularly\n• Use different keys for development and production\n• Revoke compromised keys immediately"
        }
      ]
    },
    "calls-api": {
      title: "Calls API Reference",
      sections: [
        {
          title: "POST /v1/calls",
          content: "Initiate a new AI voice call with specified scenario and parameters."
        },
        {
          title: "GET /v1/calls",
          content: "List all calls with optional filtering by date range, status, or scenario."
        },
        {
          title: "GET /v1/calls/:id",
          content: "Retrieve detailed information about a specific call including transcript and sentiment analysis."
        },
        {
          title: "DELETE /v1/calls/:id",
          content: "Delete a call recording and its associated data."
        }
      ]
    },
    "analytics": {
      title: "Analytics API",
      sections: [
        {
          title: "GET /v1/analytics/overview",
          content: "Get high-level metrics including total calls, success rate, average duration, and sentiment distribution."
        },
        {
          title: "GET /v1/analytics/trends",
          content: "Retrieve time-series data for calls, sentiment, and performance over specified date ranges."
        },
        {
          title: "Response Format",
          content: `{
  "total_calls": 1234,
  "success_rate": 0.94,
  "avg_duration": 180,
  "sentiment": {
    "positive": 0.65,
    "neutral": 0.25,
    "negative": 0.10
  }
}`
        }
      ]
    },
    "webhooks": {
      title: "Webhook Events",
      sections: [
        {
          title: "call.started",
          content: "Triggered when a new call is initiated. Contains call ID and initial parameters."
        },
        {
          title: "call.completed",
          content: "Triggered when a call finishes. Includes full transcript, sentiment analysis, and billing information."
        },
        {
          title: "call.escalated",
          content: "Triggered when AI escalates to human agent. Contains reason for escalation."
        },
        {
          title: "transcript.updated",
          content: "Triggered in real-time as transcript is generated during the call."
        }
      ]
    },
    "testing": {
      title: "Testing Portal",
      sections: [
        {
          title: "Simulation Scenarios",
          content: "Test your integration with pre-built scenarios: Banking, Healthcare, Retail, Insurance, Telecom."
        },
        {
          title: "Test Mode",
          content: "All accounts have access to test mode where calls are simulated and not billed."
        },
        {
          title: "Voice Synthesis",
          content: "Test scenarios use browser-based voice synthesis to simulate realistic call flows without using API credits."
        }
      ]
    }
  };

  return (
    <PublicLayout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <div className="text-center mb-12">
          <h1 className="text-4xl lg:text-5xl font-bold mb-4">
            API{" "}
            <span className="bg-gradient-to-r from-indigo-400 to-cyan-400 bg-clip-text text-transparent">
              Documentation
            </span>
          </h1>
          <p className="text-xl text-muted-foreground max-w-3xl mx-auto">
            Complete API reference and integration guides for the Zyvra platform.
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          <div className="lg:col-span-1">
            <Card className="sticky top-20">
              <CardContent className="p-4">
                <div className="space-y-1">
                  {sections.map((section) => (
                    <Button
                      key={section.id}
                      variant={activeSection === section.id ? "secondary" : "ghost"}
                      className="w-full justify-start"
                      onClick={() => setActiveSection(section.id)}
                      data-testid={`button-nav-${section.id}`}
                    >
                      <section.icon className="w-4 h-4 mr-2" />
                      {section.title}
                    </Button>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          <div className="lg:col-span-3">
            <Card>
              <CardContent className="p-8">
                <h2 className="text-3xl font-bold mb-8">{content[activeSection as keyof typeof content].title}</h2>
                <div className="space-y-8">
                  {content[activeSection as keyof typeof content].sections.map((section, index) => (
                    <div key={index}>
                      <h3 className="text-xl font-semibold mb-3">{section.title}</h3>
                      <div className="text-muted-foreground whitespace-pre-wrap">
                        {section.content.includes('curl') || section.content.includes('{') ? (
                          <pre className="bg-muted p-4 rounded-md overflow-x-auto">
                            <code>{section.content}</code>
                          </pre>
                        ) : (
                          <p>{section.content}</p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </PublicLayout>
  );
}
