"use client"

import { useMemo, useState } from "react"
import { PageHeader } from "@/components/page-header"
import { servers } from "@/lib/data"
import type { WireGuardInterface } from "@/lib/data"
import { DataPageCard } from "@/components/data-page-card"
import { DataPageToolbar } from "@/components/data-page-toolbar"
import {
  WireguardDataGrid,
  type WgIfaceWithServer,
} from "@/components/data-grids/wireguard-data-grid"
import { Button } from "@/components/ui/button"
import { Frame, FramePanel } from "@/components/reui/frame"
import { IconTile } from "@/components/reui/icon-tile"
import { OpsPanel } from "@/components/ops-panel"
import { cn } from "@/lib/utils"
import {
  Sheet, SheetContent, SheetHeader, SheetTitle,
  SheetDescription, SheetFooter, SheetClose,
} from "@/components/ui/sheet"
import {
  ShieldCheckIcon, PlusIcon, KeyRoundIcon,
  CodeXmlIcon, UsersIcon, ActivityIcon,
  CopyIcon, CheckIcon,
} from "lucide-react"

// ─── collect all WireGuard interfaces from all servers ────────────────────────

function collectInterfaces(): WgIfaceWithServer[] {
  const result: WgIfaceWithServer[] = []
  for (const srv of servers) {
    for (const wg of srv.wireGuardIfaces ?? []) {
      result.push({
        ...wg,
        serverId: srv.id,
        serverName: srv.name,
        serverCountry: srv.country,
      })
    }
  }
  return result
}

// ─── helpers ──────────────────────────────────────────────────────────────────

// ─── RSC generator ────────────────────────────────────────────────────────────

function generateWgRsc(iface: WgIfaceWithServer): string {
  const lines: string[] = []
  lines.push(`# WireGuard — ${iface.name} · ${iface.serverName}`)
  lines.push(`# RouterOS 7.x`)
  lines.push(``)
  lines.push(`/interface wireguard add \\`)
  lines.push(`  name=${iface.name} \\`)
  lines.push(`  listen-port=${iface.listenPort} \\`)
  lines.push(`  mtu=${iface.mtu} \\`)
  if (iface.comment) lines.push(`  comment="${iface.comment}" \\`)
  if (!iface.enabled) lines.push(`  disabled=yes \\`)
  lines.push(``)
  for (const p of iface.peers) {
    lines.push(`/interface wireguard peers add \\`)
    lines.push(`  interface=${iface.name} \\`)
    lines.push(`  public-key="${p.publicKey}" \\`)
    lines.push(`  allowed-address=${p.allowedIps.join(",")} \\`)
    if (p.endpoint) lines.push(`  endpoint-address=${p.endpoint.split(":")[0]} \\`)
    if (p.endpoint) lines.push(`  endpoint-port=${p.endpoint.split(":")[1] ?? "13231"} \\`)
    if (p.persistent) lines.push(`  persistent-keepalive=25 \\`)
    if (p.comment) lines.push(`  comment="${p.comment}" \\`)
    lines.push(``)
  }
  return lines.join("\n")
}

// ─── Export Sheet ─────────────────────────────────────────────────────────────

function ExportSheet({ open, iface, onClose }: {
  open: boolean; iface: WgIfaceWithServer | null; onClose: () => void
}) {
  const [copied, setCopied] = useState(false)
  const code = useMemo(() => iface ? generateWgRsc(iface) : "", [iface])

  function handleCopy() {
    navigator.clipboard.writeText(code).then(() => {
      setCopied(true); setTimeout(() => setCopied(false), 2000)
    })
  }

  return (
    <Sheet open={open} onOpenChange={(v) => { if (!v) onClose() }}>
      <SheetContent className="flex flex-col overflow-hidden p-0 gap-0 sm:max-w-2xl">
        <SheetHeader className="shrink-0 px-6 pt-5 pb-4 border-b">
          <div className="flex items-start justify-between gap-4">
            <div>
              <SheetTitle>Экспорт WireGuard</SheetTitle>
              <SheetDescription>RouterOS 7.x · /interface wireguard + peers</SheetDescription>
            </div>
            <Button variant="outline" size="sm" className="shrink-0" onClick={handleCopy}>
              {copied
                ? <><CheckIcon className="size-3.5 text-emerald-500" />Скопировано</>
                : <><CopyIcon className="size-3.5" />Копировать</>}
            </Button>
          </div>
        </SheetHeader>
        <div className="flex-1 overflow-y-auto">
          <pre className="px-6 py-5 text-[12px] font-mono leading-relaxed text-foreground/85 whitespace-pre select-all">
            {code.split("\n").map((line, i) => {
              const isComment = line.startsWith("#")
              const isCmd = line.trimStart().startsWith("/interface")
              const isParam = /^\s+[a-z]/.test(line)
              return (
                <span key={i} className={
                  isComment ? "text-muted-foreground"
                  : isCmd    ? "text-sky-400"
                  : isParam  ? "text-violet-300"
                  : "text-foreground"
                }>
                  {line}{"\n"}
                </span>
              )
            })}
          </pre>
        </div>
        <SheetFooter className="shrink-0 px-6 py-4 border-t flex-row gap-2">
          <SheetClose render={<Button variant="outline" className="flex-1" />}>Закрыть</SheetClose>
          <Button className="flex-1" onClick={handleCopy}>
            {copied ? <CheckIcon className="size-4" /> : <CopyIcon className="size-4" />}
            {copied ? "Скопировано" : "Копировать .rsc"}
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}

// ════════════════════════════════════════════════════════════════════════════
export default function WireGuardPage() {
  const allIfaces = useMemo(() => collectInterfaces(), [])

  const [search, setSearch] = useState("")
  const [exportIface, setExportIface] = useState<WgIfaceWithServer | null>(null)

  const filtered = useMemo(() => {
    if (!search) return allIfaces
    const q = search.toLowerCase()
    return allIfaces.filter((i) =>
      i.name.includes(q) ||
      i.serverName.toLowerCase().includes(q) ||
      i.peers.some((p) => p.allowedIps.some((a) => a.includes(q)) || (p.endpoint ?? "").includes(q))
    )
  }, [allIfaces, search])

  const totalPeers   = allIfaces.reduce((s, i) => s + i.peers.length, 0)
  const onlinePeers  = allIfaces.reduce((s, i) => s + i.peers.filter((p) => !!p.latestHandshake).length, 0)
  const upIfaces     = allIfaces.filter((i) => i.status === "up").length

  return (
    <div className="flex flex-col h-full">
      <PageHeader
        crumbs={[{ label: "Управление" }, { label: "WireGuard" }]}
        actions={
          <>
            <Button size="sm">
              <PlusIcon className="size-4" />Новый интерфейс
            </Button>
          </>
        }
      />

      <div className="flex-1 overflow-y-auto p-6">
        <div className="flex flex-col gap-5">

          {/* KPI */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {[
              { label: "Интерфейсов",   value: allIfaces.length,            icon: <ShieldCheckIcon className="size-4 text-muted-foreground" /> },
              { label: "Активных (UP)", value: upIfaces,                    icon: <ActivityIcon className="size-4 text-emerald-500" /> },
              { label: "Всего пиров",   value: totalPeers,                  icon: <UsersIcon className="size-4 text-sky-400" /> },
              { label: "Пиров онлайн",  value: `${onlinePeers}/${totalPeers}`, icon: <KeyRoundIcon className="size-4 text-violet-400" /> },
            ].map((s) => (
              <Frame key={s.label} className="h-full">
                <FramePanel className="relative isolate flex h-full items-start gap-3">
                  <IconTile variant="elevated" aria-hidden="true" className="size-10.5 text-muted-foreground">
                    {s.icon}
                  </IconTile>
                  <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                    <p className="text-muted-foreground text-sm font-medium">{s.label}</p>
                    <p className="text-2xl leading-none font-bold tabular-nums">{s.value}</p>
                  </div>
                </FramePanel>
              </Frame>
            ))}
          </div>

          {/* Info banner */}
          <div className="flex items-start gap-3 rounded-lg bg-sky-500/5 border border-sky-500/20 px-4 py-3 text-sm">
            <ShieldCheckIcon className="size-5 text-sky-500 shrink-0 mt-0.5" />
            <div>
              <p className="font-medium text-sky-600 dark:text-sky-400">WireGuard — рекомендуемый туннельный протокол в RouterOS 7.x</p>
              <p className="text-muted-foreground text-xs mt-0.5">
                Доступен с RouterOS 7.1+. Более высокая производительность и безопасность по сравнению с GRE+IPsec.
                Ключи генерируются командой <code className="font-mono bg-muted px-1 rounded">/interface/wireguard/print</code>.
              </p>
            </div>
          </div>

          {/* Search + table */}
          <DataPageCard>
            <DataPageToolbar
              search={search}
              onSearchChange={setSearch}
              searchPlaceholder="Поиск по имени, серверу, IP…"
              countLabel={`${filtered.length} интерфейсов`}
            />
            <WireguardDataGrid
              interfaces={filtered}
              onExport={setExportIface}
            />
          </DataPageCard>

          {/* RouterOS reference */}
          <OpsPanel title="RouterOS 7 · /interface wireguard — быстрые команды" contentClassName="px-5 py-4">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-xs font-mono">
                {[
                  {
                    title: "Создать интерфейс",
                    lines: [
                      "/interface wireguard add \\",
                      "  name=wg0 \\",
                      "  listen-port=13231 \\",
                      "  mtu=1420",
                    ],
                  },
                  {
                    title: "Добавить пира",
                    lines: [
                      "/interface wireguard peers add \\",
                      "  interface=wg0 \\",
                      '  public-key="<ключ>" \\',
                      "  allowed-address=10.0.0.2/32 \\",
                      "  endpoint-address=1.2.3.4 \\",
                      "  persistent-keepalive=25",
                    ],
                  },
                  {
                    title: "Назначить IP",
                    lines: [
                      "/ip address add \\",
                      "  address=10.210.0.1/30 \\",
                      "  interface=wg0",
                      "",
                      "# Статус:",
                      "/interface wireguard print",
                    ],
                  },
                ].map((b) => (
                  <div key={b.title}>
                    <p className="font-sans font-semibold text-foreground/80 mb-1.5 text-[11px] uppercase tracking-wide">{b.title}</p>
                    <pre className="bg-zinc-950 rounded-md p-2.5 text-zinc-300 text-[11px] leading-relaxed overflow-x-auto">
                      {b.lines.join("\n")}
                    </pre>
                  </div>
                ))}
              </div>
          </OpsPanel>

        </div>
      </div>

      <ExportSheet
        open={!!exportIface}
        iface={exportIface}
        onClose={() => setExportIface(null)}
      />
    </div>
  )
}
