"use client";

import { ScrollArea } from "./ui/scroll-area";
import { Badge } from "./ui/badge";
import {
  BookOpen,
  Code2,
  Database,
  Shield,
  Zap,
  Server,
  Cable,
  Box,
  Settings2,
  Heart,
} from "lucide-react";

function Section({
  icon: Icon,
  title,
  children,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  children: React.ReactNode;
}) {
  return (
    <section className="rounded-lg border border-border bg-card">
      <div className="flex items-center gap-2 border-b border-border px-4 py-2.5">
        <Icon className="h-3.5 w-3.5 text-primary" />
        <h3 className="text-xs font-semibold text-foreground">{title}</h3>
      </div>
      <div className="px-4 py-3 text-prose-sm text-foreground-subtle leading-relaxed space-y-2">
        {children}
      </div>
    </section>
  );
}

function Code({ children }: { children: string }) {
  return (
    <pre className="overflow-x-auto rounded border border-border bg-muted px-3 py-2 font-mono text-body-sm leading-relaxed text-foreground-subtle whitespace-pre">
      {children}
    </pre>
  );
}

function InlineCode({ children }: { children: React.ReactNode }) {
  return (
    <code className="rounded bg-muted px-1 py-0.5 font-mono text-body-sm text-primary">
      {children}
    </code>
  );
}

export default function SdkDocs() {
  return (
    <div className="flex flex-1 flex-col min-h-0">
      <div className="flex items-center gap-2 border-b border-border px-4 py-2">
        <BookOpen className="h-3.5 w-3.5 text-primary" />
        <h2 className="text-xs font-semibold text-foreground">
          SDK Documentation
        </h2>
        <Badge variant="default" className="text-tiny">
          v1.2.0
        </Badge>
      </div>

      <ScrollArea className="flex-1">
        <div className="mx-auto max-w-3xl space-y-4 p-5">
          {/* Hero */}
          <div className="rounded-lg border border-primary/20 bg-primary/5 px-5 py-4">
            <h1 className="text-lg font-bold text-foreground tracking-tight">
              AthenaClient SDK
            </h1>
            <p className="text-xs text-muted-foreground mt-1">
              Builder-based Rust client that unifies Supabase, PostgreSQL,
              Scylla, Neon, and Postgrest backends in one surface.
            </p>
            <div className="flex flex-wrap gap-1.5 mt-2.5">
              {[
                "Supabase",
                "PostgreSQL",
                "ScyllaDB",
                "Neon",
                "Postgrest",
                "Native",
              ].map((b) => (
                <Badge key={b} variant="outline" className="text-tiny">
                  {b}
                </Badge>
              ))}
            </div>
          </div>

          <Section icon={Zap} title="Quick Start">
            <Code>{`use athena_rs::{AthenaClient, BackendType};

// Simple constructor
let client = AthenaClient::new(url, key);

// With specific backend
let client = AthenaClient::new_with_backend(url, key, BackendType::Supabase);

// Builder pattern (recommended)
let client = AthenaClient::builder()
    .backend(BackendType::Supabase)
    .url("https://project.supabase.co")
    .key("service-role-key")
    .health_tracking(true)
    .build()
    .await?;`}</Code>
          </Section>

          <Section icon={Code2} title="Query Builders">
            <p>
              The SDK exposes <InlineCode>select</InlineCode>,{" "}
              <InlineCode>insert</InlineCode>, <InlineCode>update</InlineCode>,
              and <InlineCode>delete</InlineCode> builders with chainable
              methods.
            </p>
            <Code>{`use athena_rs::client::query_builder::OrderDirection;

// SELECT with filters, ordering, pagination
let rows = client
    .select("users")
    .columns(["id", "email"])
    .where_eq("status", "active")
    .where_gt("created_at", "2025-01-01")
    .order_by("created_at", OrderDirection::Desc)
    .limit(10)
    .offset(0)
    .execute()
    .await?;

// INSERT
client
    .insert("logs")
    .payload(json!({ "message": "SDK initialized" }))
    .execute()
    .await?;`}</Code>
            <p className="text-muted-foreground text-body-sm">
              Filters: <InlineCode>where_eq</InlineCode>,{" "}
              <InlineCode>where_gt</InlineCode>,{" "}
              <InlineCode>where_in</InlineCode>,{" "}
              <InlineCode>order_by</InlineCode>, <InlineCode>limit</InlineCode>,{" "}
              <InlineCode>offset</InlineCode>
            </p>
          </Section>

          <Section icon={Database} title="Raw Execution">
            <div className="grid grid-cols-2 gap-3">
              <div className="rounded border border-border bg-muted-card p-3">
                <p className="text-caption font-medium text-muted-foreground uppercase tracking-wider mb-1">
                  SQL
                </p>
                <code className="text-body-sm font-mono text-foreground">
                  execute_sql(&quot;SELECT ...&quot;)
                </code>
                <p className="text-caption text-muted-foreground mt-1">
                  Backend-agnostic SQL execution
                </p>
              </div>
              <div className="rounded border border-border bg-muted-card p-3">
                <p className="text-caption font-medium text-muted-foreground uppercase tracking-wider mb-1">
                  CQL
                </p>
                <code className="text-body-sm font-mono text-foreground">
                  execute_cql(&quot;SELECT ...&quot;)
                </code>
                <p className="text-caption text-muted-foreground mt-1">
                  Cassandra / ScyllaDB queries
                </p>
              </div>
            </div>
          </Section>

          <Section icon={Settings2} title="Configuration Objects">
            <div className="space-y-2">
              <div className="rounded border border-border p-2.5">
                <p className="text-body-sm font-semibold text-foreground">
                  ConnectionConfig
                </p>
                <p className="text-caption text-muted-foreground">
                  <InlineCode>url</InlineCode>, <InlineCode>key</InlineCode>{" "}
                  (optional), <InlineCode>ssl</InlineCode>,{" "}
                  <InlineCode>port</InlineCode>,{" "}
                  <InlineCode>database</InlineCode>
                </p>
              </div>
              <div className="rounded border border-border p-2.5">
                <p className="text-body-sm font-semibold text-foreground">
                  PoolConfig
                </p>
                <p className="text-caption text-muted-foreground">
                  <InlineCode>max_connections</InlineCode> (50),{" "}
                  <InlineCode>min_connections</InlineCode> (5),{" "}
                  <InlineCode>connection_timeout</InlineCode> (5s),{" "}
                  <InlineCode>idle_timeout</InlineCode> (300s)
                </p>
              </div>
              <div className="rounded border border-border p-2.5">
                <p className="text-body-sm font-semibold text-foreground">
                  HealthConfig
                </p>
                <p className="text-caption text-muted-foreground">
                  <InlineCode>check_interval</InlineCode> (30s),{" "}
                  <InlineCode>circuit_breaker_threshold</InlineCode> (5),{" "}
                  <InlineCode>circuit_breaker_timeout</InlineCode> (60s)
                </p>
              </div>
            </div>
          </Section>

          <Section icon={Heart} title="Health Tracking & Circuit Breaker">
            <p>
              The Supabase backend wraps clients in{" "}
              <InlineCode>HealthAwareSupabaseClient</InlineCode> implementing a
              circuit breaker pattern.
            </p>
            <div className="grid grid-cols-3 gap-2 mt-2">
              <div className="rounded border border-border p-2 text-center">
                <code className="text-caption font-mono text-foreground">
                  is_offline()
                </code>
                <p className="text-tiny text-muted-foreground mt-0.5">
                  Check blocked
                </p>
              </div>
              <div className="rounded border border-border p-2 text-center">
                <code className="text-caption font-mono text-foreground">
                  force_offline(dur)
                </code>
                <p className="text-tiny text-muted-foreground mt-0.5">
                  Test mode
                </p>
              </div>
              <div className="rounded border border-border p-2 text-center">
                <code className="text-caption font-mono text-foreground">
                  reset_health()
                </code>
                <p className="text-tiny text-muted-foreground mt-0.5">
                  Clear failures
                </p>
              </div>
            </div>
          </Section>

          <Section icon={Cable} title="Environment Initialization">
            <p>Build Supabase backends directly from environment variables:</p>
            <Code>{`let backend = SupabaseBackend::from_env(
    "ATHENA_SUPABASE_URL",
    "ATHENA_SUPABASE_KEY",
)?;

let client = AthenaClient::builder()
    .backend(BackendType::Supabase)
    .url(backend.config().connection.url.clone())
    .key(backend.config().connection.key.clone().unwrap())
    .build()
    .await?;`}</Code>
          </Section>

          <Section icon={Box} title="Backend Types">
            <div className="flex flex-wrap gap-1.5">
              {[
                { name: "Native", desc: "Default SQL" },
                { name: "Supabase", desc: "REST + RPC" },
                { name: "Postgrest", desc: "PostgREST" },
                { name: "Scylla", desc: "CQL" },
                { name: "Neon", desc: "Serverless Pg" },
                { name: "PostgreSQL", desc: "SQLx pools" },
              ].map((b) => (
                <div
                  key={b.name}
                  className="rounded border border-border px-2.5 py-1.5 bg-muted-panel"
                >
                  <span className="text-body-sm font-mono font-medium text-foreground">
                    {b.name}
                  </span>
                  <span className="text-tiny text-muted-foreground ml-1.5">
                    {b.desc}
                  </span>
                </div>
              ))}
            </div>
            <p className="text-caption text-muted-foreground mt-2">
              Use{" "}
              <InlineCode>
                new_with_backend_name(&quot;supabase&quot;)
              </InlineCode>{" "}
              for string-based backend selection.
            </p>
          </Section>

          <Section icon={Server} title="Drivers">
            <div className="space-y-2">
              <div className="rounded border border-border p-2.5">
                <div className="flex items-center gap-1.5">
                  <Badge variant="default" className="text-2xs">
                    PostgreSQL
                  </Badge>
                  <span className="text-caption text-muted-foreground">
                    SQLx pools
                  </span>
                </div>
                <p className="text-caption text-muted-foreground mt-1">
                  Connection:{" "}
                  <InlineCode>postgres://user:pass@host:port/db</InlineCode>.
                  Honors PoolConfig. Maps X-Athena-Client to pool entries.
                </p>
              </div>
              <div className="rounded border border-border p-2.5">
                <div className="flex items-center gap-1.5">
                  <Badge variant="default" className="text-2xs">
                    ScyllaDB
                  </Badge>
                  <span className="text-caption text-muted-foreground">
                    Native CQL
                  </span>
                </div>
                <p className="text-caption text-muted-foreground mt-1">
                  Host/port pairs via <InlineCode>scylla::Session</InlineCode>.
                  Supports <InlineCode>execute_cql</InlineCode> + health
                  tracking.
                </p>
              </div>
              <div className="rounded border border-border p-2.5">
                <div className="flex items-center gap-1.5">
                  <Badge variant="default" className="text-2xs">
                    Supabase
                  </Badge>
                  <span className="text-caption text-muted-foreground">
                    REST + RPC
                  </span>
                </div>
                <p className="text-caption text-muted-foreground mt-1">
                  Backed by <InlineCode>supabase_rs</InlineCode>. Override with{" "}
                  <InlineCode>x-supabase-url</InlineCode> /{" "}
                  <InlineCode>x-supabase-key</InlineCode> headers. Circuit
                  breaker built-in.
                </p>
              </div>
            </div>
          </Section>

          <Section icon={Shield} title="Authentication">
            <p>All gateway endpoints require authentication headers:</p>
            <div className="grid grid-cols-2 gap-2 mt-2">
              {[
                ["apikey / x-api-key", "API key for every request"],
                ["X-Athena-Client", "Selects Postgres pool"],
                ["X-User-Id", "Audit — required for insert/delete"],
                ["X-Company-Id", "Audit — required for insert/delete"],
                ["X-Organization-Id", "Audit traceability"],
                ["X-Athena-Key", "Admin key (ATHENA_KEY_12)"],
              ].map(([header, desc]) => (
                <div
                  key={header}
                  className="rounded border border-border px-2 py-1.5"
                >
                  <code className="text-caption font-mono text-primary">
                    {header}
                  </code>
                  <p className="text-tiny text-muted-foreground mt-0.5">
                    {desc}
                  </p>
                </div>
              ))}
            </div>
          </Section>
        </div>
      </ScrollArea>
    </div>
  );
}
