import { useState } from "react";
import Footer from "@/components/Footer";
import Header from "@/components/Header";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useDownload } from "@/hooks/useDownload";
import {
  Database,
  Download,
  FileOutput,
  Plug,
  Shield,
  Sparkles,
  Server,
  Lock,
  Globe,
  Mail,
  RefreshCw,
  HardDrive,
  Terminal,
  Check,
  Copy,
} from "lucide-react";

const GITHUB_URL = "https://github.com/byaan-ai/byaan";
const SELF_HOST_README = "https://github.com/byaan-ai/byaan/blob/main/docs/self-hosted/README.md";
const INSTALL_CMD =
  "curl -fsSL https://downloads.byaan.ai/docker/install.sh | bash";

const quickStartSteps = [
  "Download Byaan for macOS.",
  "Connect a database or upload CSV, Excel, Parquet, or JSON files.",
  "Let Byaan inspect schemas and learn your business definitions.",
  "Ask questions in natural language and turn answers into dashboards.",
];

const capabilities = [
  {
    icon: Database,
    title: "Connect to your data",
    description:
      "PostgreSQL, MongoDB, MySQL, MariaDB, SQLite, MSSQL, DuckDB, plus CSV, Excel, Parquet, and JSON files.",
  },
  {
    icon: Sparkles,
    title: "Ask in plain English",
    description:
      "Byaan converts business questions into read-only analysis and preserves your metric definitions and table context.",
  },
  {
    icon: FileOutput,
    title: "Build dashboards",
    description:
      "Generate interactive dashboards with filters, charts, and reusable analysis patterns from notebooks.",
  },
  {
    icon: Plug,
    title: "Use MCP",
    description:
      "Expose Byaan as an MCP server for Claude Code, Cursor, Codex, and other MCP-compatible clients.",
  },
  {
    icon: Shield,
    title: "Read-only by design",
    description:
      "DDL and DML are blocked. Production databases stay safe — Byaan can only inspect, never write.",
  },
  {
    icon: Download,
    title: "Export and share",
    description:
      "Export standalone HTML dashboards, share notebook links, or generate PDFs for stakeholders.",
  },
];

const requiredEnv = [
  { name: "APP_SECRET", desc: "JWT signing + encryption key (auto-generated by installer)" },
  { name: "MASTER_USER_EMAIL", desc: "Admin user email" },
  { name: "MASTER_USER_PASSWORD", desc: "Admin password (min 8 characters)" },
  { name: "ORG_NAME", desc: "Your organization name" },
];

const optionalEnv = [
  { name: "ENCRYPTION_KEY", desc: "Separate 32-byte hex key for credential encryption (recommended)" },
  { name: "DOMAIN", desc: "Custom domain (e.g. app.yourcompany.com) — enables Let's Encrypt HTTPS" },
  { name: "ACME_EMAIL", desc: "Email for Let's Encrypt cert notifications" },
  { name: "GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET", desc: "Google OAuth (optional SSO)" },
  { name: "SMTP_HOST / SMTP_USERNAME / SMTP_PASSWORD", desc: "SMTP for team invites (optional)" },
];

const teamCommands = [
  { cmd: "./start.sh", desc: "Start Byaan" },
  { cmd: "./start.sh stop", desc: "Stop Byaan" },
  { cmd: "./start.sh update", desc: "Update to latest version" },
  { cmd: "./start.sh logs", desc: "View all logs" },
  { cmd: "./start.sh logs backend", desc: "View backend logs only" },
  { cmd: "./start.sh logs caddy", desc: "View web server logs" },
  { cmd: "./start.sh logs postgres", desc: "View database logs" },
  { cmd: "./start.sh status", desc: "Check if running" },
  { cmd: "./start.sh remove", desc: "Remove container, keep data" },
  { cmd: "./start.sh remove --data", desc: "Remove container and all data" },
];

const tocSections = [
  { id: "quick-start", label: "Quick start" },
  { id: "core", label: "Core capabilities" },
  { id: "self-host", label: "Team Version" },
  { id: "updates", label: "Updates & logs" },
  { id: "security", label: "Security model" },
];

const Documentation = () => {
  const { isMac, architecture, appleUrl, intelUrl } = useDownload();
  const downloadUrl =
    architecture === "intel" ? intelUrl : architecture === "apple-silicon" ? appleUrl : appleUrl;
  const downloadHref = isMac && architecture !== "unknown" ? downloadUrl : appleUrl;
  const [copied, setCopied] = useState(false);

  const copyInstall = async () => {
    try {
      await navigator.clipboard.writeText(INSTALL_CMD);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1400);
    } catch {
      /* clipboard unavailable */
    }
  };

  return (
    <div className="min-h-screen bg-background">
      <Header />

      <main className="container mx-auto max-w-5xl px-4 pt-28 pb-20">
        <section className="mb-12">
          <div className="mb-6 inline-flex rounded-full border border-primary/20 bg-primary/10 px-4 py-1.5">
            <span className="font-mono text-sm text-primary">Documentation</span>
          </div>
          <h1 className="mb-6 max-w-3xl font-mono text-4xl font-bold leading-tight md:text-6xl">
            Run Byaan locally or deploy the Team Version
          </h1>
          <p className="max-w-3xl text-lg leading-relaxed text-muted-foreground">
            The Mac app is free for individuals and runs entirely on your machine. The team
            version is one-line Docker — multi-user auth, RBAC, Slack, Google OAuth, and
            automatic HTTPS, all in your VPC.
          </p>
          <div className="mt-8 flex flex-col gap-3 sm:flex-row">
            <Button asChild size="lg" className="gap-2">
              <a href={downloadHref}>
                <Download className="h-4 w-4" />
                Download for Mac
              </a>
            </Button>
            <Button asChild variant="outline" size="lg" className="gap-2">
              <a href="#self-host">
                <Server className="h-4 w-4" />
                Team Version
              </a>
            </Button>
            <Button asChild variant="outline" size="lg">
              <a href={GITHUB_URL} target="_blank" rel="noopener noreferrer">
                Star on GitHub
              </a>
            </Button>
          </div>

          <nav className="mt-10 flex flex-wrap items-center gap-2 border-t border-border pt-6">
            <span className="mr-2 font-mono text-xs uppercase tracking-wider text-muted-foreground">
              On this page
            </span>
            {tocSections.map((s) => (
              <a
                key={s.id}
                href={`#${s.id}`}
                className="rounded-full border border-border bg-card/50 px-3 py-1 font-mono text-xs text-muted-foreground transition-colors hover:border-primary/40 hover:text-primary"
              >
                {s.label}
              </a>
            ))}
          </nav>
        </section>

        <section id="quick-start" className="mb-16 scroll-mt-24">
          <h2 className="mb-6 font-mono text-3xl font-bold">Quick start</h2>
          <div className="grid gap-4 md:grid-cols-4">
            {quickStartSteps.map((step, index) => (
              <Card key={step} className="border-border bg-card p-5">
                <div className="mb-4 font-mono text-sm text-primary">0{index + 1}</div>
                <p className="text-sm leading-relaxed text-muted-foreground">{step}</p>
              </Card>
            ))}
          </div>
        </section>

        <section id="core" className="mb-16 scroll-mt-24">
          <h2 className="mb-6 font-mono text-3xl font-bold">Core capabilities</h2>
          <div className="grid gap-5 md:grid-cols-2 lg:grid-cols-3">
            {capabilities.map((capability) => {
              const Icon = capability.icon;
              return (
                <Card key={capability.title} className="border-border bg-card p-6">
                  <div className="mb-4 inline-flex rounded-lg border border-primary/20 bg-primary/10 p-3">
                    <Icon className="h-5 w-5 text-primary" />
                  </div>
                  <h3 className="mb-2 font-mono text-lg font-semibold">{capability.title}</h3>
                  <p className="text-sm leading-relaxed text-muted-foreground">
                    {capability.description}
                  </p>
                </Card>
              );
            })}
          </div>
        </section>

        <section id="self-host" className="mb-16 scroll-mt-24">
          <div className="mb-6 flex items-baseline justify-between gap-4">
            <h2 className="font-mono text-3xl font-bold">Team Version</h2>
            <a
              href={SELF_HOST_README}
              target="_blank"
              rel="noopener noreferrer"
              className="font-mono text-xs text-primary hover:underline"
            >
              Full README →
            </a>
          </div>
          <p className="mb-8 max-w-3xl text-muted-foreground">
            One container ships PostgreSQL, the FastAPI backend, the React frontend, and Caddy.
            Live on port 8080 in five minutes. AGPL licensed.
          </p>

          <Card className="mb-8 border-border bg-card p-6">
            <div className="mb-3 flex items-center gap-2 font-mono text-sm font-semibold">
              <Terminal className="h-4 w-4 text-primary" />
              One-line install
            </div>
            <div className="relative rounded-lg border border-border bg-background/60 p-4 pr-12 font-mono text-xs leading-relaxed">
              <span className="break-all text-foreground">{INSTALL_CMD}</span>
              <button
                onClick={copyInstall}
                className="absolute right-3 top-3 rounded border border-border bg-card p-1.5 text-muted-foreground transition-colors hover:border-primary/40 hover:text-primary"
                title="Copy"
              >
                {copied ? (
                  <Check className="h-3.5 w-3.5 text-primary" />
                ) : (
                  <Copy className="h-3.5 w-3.5" />
                )}
              </button>
            </div>
            <p className="mt-4 text-sm text-muted-foreground">
              Drops <code className="rounded bg-muted px-1.5 py-0.5 text-xs">start.sh</code>{" "}
              and <code className="rounded bg-muted px-1.5 py-0.5 text-xs">.env</code> into a{" "}
              <code className="rounded bg-muted px-1.5 py-0.5 text-xs">byaan</code>{" "}
              directory. Set admin email, password, and org name in{" "}
              <code className="rounded bg-muted px-1.5 py-0.5 text-xs">.env</code>, then run{" "}
              <code className="rounded bg-muted px-1.5 py-0.5 text-xs">./start.sh</code>.
            </p>
          </Card>

          <h3 className="mb-3 font-mono text-lg font-semibold">Requirements</h3>
          <ul className="mb-8 grid gap-2 text-sm text-muted-foreground md:grid-cols-2">
            <li className="flex items-start gap-2">
              <Server className="mt-0.5 h-4 w-4 flex-shrink-0 text-primary" />
              Linux server (Ubuntu 20.04+, Debian 11+, or any Docker-compatible OS)
            </li>
            <li className="flex items-start gap-2">
              <HardDrive className="mt-0.5 h-4 w-4 flex-shrink-0 text-primary" />
              2 GB RAM minimum (4 GB recommended), 10 GB disk
            </li>
            <li className="flex items-start gap-2">
              <Globe className="mt-0.5 h-4 w-4 flex-shrink-0 text-primary" />
              Ports 80 and 443 (or 8080 for local)
            </li>
            <li className="flex items-start gap-2">
              <Lock className="mt-0.5 h-4 w-4 flex-shrink-0 text-primary" />
              Docker installed
            </li>
          </ul>

          <h3 className="mb-3 font-mono text-lg font-semibold">Required environment variables</h3>
          <Card className="mb-8 overflow-hidden border-border bg-card">
            <table className="w-full text-sm">
              <thead className="border-b border-border bg-muted/30">
                <tr>
                  <th className="px-4 py-2 text-left font-mono text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Variable
                  </th>
                  <th className="px-4 py-2 text-left font-mono text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Description
                  </th>
                </tr>
              </thead>
              <tbody>
                {requiredEnv.map((row, i) => (
                  <tr key={row.name} className={i > 0 ? "border-t border-border" : ""}>
                    <td className="px-4 py-3 font-mono text-xs text-primary">{row.name}</td>
                    <td className="px-4 py-3 text-muted-foreground">{row.desc}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          <h3 className="mb-3 font-mono text-lg font-semibold">Optional</h3>
          <Card className="mb-8 overflow-hidden border-border bg-card">
            <table className="w-full text-sm">
              <thead className="border-b border-border bg-muted/30">
                <tr>
                  <th className="px-4 py-2 text-left font-mono text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Variable
                  </th>
                  <th className="px-4 py-2 text-left font-mono text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Description
                  </th>
                </tr>
              </thead>
              <tbody>
                {optionalEnv.map((row, i) => (
                  <tr key={row.name} className={i > 0 ? "border-t border-border" : ""}>
                    <td className="px-4 py-3 font-mono text-xs text-primary">{row.name}</td>
                    <td className="px-4 py-3 text-muted-foreground">{row.desc}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          <h3 className="mb-3 font-mono text-lg font-semibold">Commands</h3>
          <Card className="mb-8 overflow-hidden border-border bg-card">
            <ul className="divide-y divide-border">
              {teamCommands.map((c) => (
                <li key={c.cmd} className="flex flex-col gap-1 px-4 py-3 sm:flex-row sm:items-center sm:gap-6">
                  <code className="font-mono text-xs text-primary sm:w-72 sm:flex-shrink-0">
                    {c.cmd}
                  </code>
                  <span className="text-sm text-muted-foreground">{c.desc}</span>
                </li>
              ))}
            </ul>
          </Card>

          <div className="grid gap-4 md:grid-cols-2">
            <Card className="border-border bg-card p-5">
              <HardDrive className="mb-3 h-5 w-5 text-primary" />
              <h4 className="mb-1 font-mono text-sm font-semibold">Backups</h4>
              <p className="text-sm leading-relaxed text-muted-foreground">
                Data lives in the <code className="rounded bg-muted px-1.5 py-0.5 text-xs">byaan_data</code>{" "}
                Docker volume. Snapshot via <code className="rounded bg-muted px-1.5 py-0.5 text-xs">pg_dump</code>{" "}
                or volume tar.
              </p>
            </Card>
            <Card className="border-border bg-card p-5">
              <Mail className="mb-3 h-5 w-5 text-primary" />
              <h4 className="mb-1 font-mono text-sm font-semibold">Team invites</h4>
              <p className="text-sm leading-relaxed text-muted-foreground">
                Configure SMTP to email invitations automatically. Or skip SMTP — invitations
                are still created and the admin copies the generated link from the Members
                page to share manually.
              </p>
            </Card>
          </div>
        </section>

        <section id="updates" className="mb-16 scroll-mt-24">
          <h2 className="mb-6 font-mono text-3xl font-bold">Updates &amp; logs</h2>
          <p className="mb-8 max-w-3xl text-muted-foreground">
            Keep your Team Version current with a single command. Data and configuration are
            preserved across updates. Use the log commands to monitor or debug any service.
          </p>

          <div className="grid gap-4 md:grid-cols-2">
            <Card className="border-border bg-card p-5">
              <RefreshCw className="mb-3 h-5 w-5 text-primary" />
              <h4 className="mb-1 font-mono text-sm font-semibold">Zero-downtime updates</h4>
              <p className="text-sm leading-relaxed text-muted-foreground">
                <code className="rounded bg-muted px-1.5 py-0.5 text-xs">./start.sh update</code>{" "}
                pulls the latest image, recreates the container, and mounts the same{" "}
                <code className="rounded bg-muted px-1.5 py-0.5 text-xs">byaan_data</code>{" "}
                volume — no data loss.
              </p>
            </Card>
            <Card className="border-border bg-card p-5">
              <Terminal className="mb-3 h-5 w-5 text-primary" />
              <h4 className="mb-1 font-mono text-sm font-semibold">Targeted log tailing</h4>
              <p className="text-sm leading-relaxed text-muted-foreground">
                Pass a service name to scope output:{" "}
                <code className="rounded bg-muted px-1.5 py-0.5 text-xs">backend</code>,{" "}
                <code className="rounded bg-muted px-1.5 py-0.5 text-xs">caddy</code>, or{" "}
                <code className="rounded bg-muted px-1.5 py-0.5 text-xs">postgres</code>. Omit
                it to follow all services at once.
              </p>
            </Card>
          </div>
        </section>

        <section id="security" className="mb-8 scroll-mt-24">
          <h2 className="mb-6 font-mono text-3xl font-bold">Security model</h2>
          <div className="space-y-4 text-muted-foreground">
            <p>
              The Mac app keeps database credentials, queries, and result data on your computer.
              You choose the model provider and keys, and Byaan connects from your environment.
            </p>
            <p>
              The team version runs in your VPC. Byaan-hosted infrastructure is never in the
              data path — credentials, queries, and results stay where you put them.
            </p>
            <p>
              Both versions are read-only by design: DDL and DML are blocked, so production
              databases can be inspected without risk of accidental writes.
            </p>
          </div>
        </section>

        <section className="rounded-lg border border-border bg-card/50 p-8 text-center">
          <h3 className="mb-2 font-mono text-xl font-semibold">Have a question?</h3>
          <p className="mb-5 text-muted-foreground">
            Open an issue or jump into discussions on GitHub.
          </p>
          <div className="flex flex-col items-center justify-center gap-3 sm:flex-row">
            <Button asChild variant="outline">
              <a
                href={`${GITHUB_URL}/discussions`}
                target="_blank"
                rel="noopener noreferrer"
              >
                GitHub Discussions
              </a>
            </Button>
            <Button asChild variant="outline">
              <a
                href={`${GITHUB_URL}/issues`}
                target="_blank"
                rel="noopener noreferrer"
              >
                Report an issue
              </a>
            </Button>
          </div>
        </section>
      </main>

      <Footer />
    </div>
  );
};

export default Documentation;
