import { ConnectionActionMenu } from '@/components/connections/connection-action-menu'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  formatBytes,
  formatNanoDelay,
  formatPPS,
  formatSpeed,
} from '@/lib/format'
import type { RemoteLinkItem } from '@/types/api'
import {
  ArrowDown,
  ArrowUp,
  Check,
  ChevronsLeftRightEllipsis,
  Copy,
  LayoutGrid,
  List,
  Network,
  Plus,
  Search,
  Plug,
  Unplug
} from "lucide-react"
import { useMemo, useState } from 'react'

interface ConnectionsPageProps {
  links: RemoteLinkItem[]
  isConnected: boolean
  onAddLink: (address: string) => Promise<{ success: boolean; message?: string }>
  onRemoveLink: (address: string) => Promise<{ success: boolean; message?: string }>
  onLinkAction: (
    address: string,
    action: 'reconnect' | 'disconnect' | 'remove'
  ) => Promise<{ success: boolean; message?: string }>
}

export function ConnectionsPage({
  links,
  onAddLink,
  onRemoveLink,
  onLinkAction,
}: ConnectionsPageProps) {
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid')
  const [searchQuery, setSearchQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState<'all' | 'up' | 'down'>('all')

  // Add Dialog State
  const [isAddOpen, setIsAddOpen] = useState(false)
  const [newAddress, setNewAddress] = useState('')
  const [addError, setAddError] = useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  // Copy Feedback state
  const [copiedAddress, setCopiedAddress] = useState<string | null>(null)

  const copyText = (text: string) => {
    navigator.clipboard.writeText(text)
    setCopiedAddress(text)
    setTimeout(() => setCopiedAddress(null), 2000)
  }

  // Summary calculations
  const stats = useMemo(() => {
    const total = links.length
    const up = links.filter((l) => l.stateCode === 2 || l.state.toLowerCase().includes('up') || l.state === 'ESTABLISHED').length
    const down = total - up
    const totalUpSpeed = links.reduce((acc, l) => acc + (l.upSpeed || 0), 0)
    const totalDownSpeed = links.reduce((acc, l) => acc + (l.downSpeed || 0), 0)
    return { total, up, down, totalUpSpeed, totalDownSpeed }
  }, [links])

  // Filtered links
  const filteredLinks = useMemo(() => {
    return links.filter((link) => {
      const matchSearch =
        searchQuery === '' ||
        link.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (link.socketAddress &&
          link.socketAddress.toLowerCase().includes(searchQuery.toLowerCase())) ||
        (link.vaddr &&
          link.vaddr.toLowerCase().includes(searchQuery.toLowerCase()))

      const isLinkUp =
        link.stateCode === 2 ||
        link.state.toLowerCase().includes('up') ||
        link.state === 'ESTABLISHED'

      if (statusFilter === 'up') return matchSearch && isLinkUp
      if (statusFilter === 'down') return matchSearch && !isLinkUp
      return matchSearch
    })
  }, [links, searchQuery, statusFilter])

  const handleAddSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newAddress.trim()) {
      setAddError('请输入远程连接 Socket 地址')
      return
    }
    setIsSubmitting(true)
    setAddError(null)
    const res = await onAddLink(newAddress.trim())
    setIsSubmitting(false)
    if (res.success) {
      setNewAddress('')
      setIsAddOpen(false)
    } else {
      setAddError(res.message || '添加连接失败')
    }
  }

  const getProtocolBadge = (address?: string) => {
    if (!address) return <Badge variant="outline">TCP</Badge>
    const lower = address.toLowerCase()
    if (lower.startsWith('udp://')) {
      return <Badge variant="secondary" className="bg-purple-500/10 text-purple-600 dark:text-purple-400 font-mono text-[10px]">UDP</Badge>
    }
    if (lower.startsWith('kltp://')) {
      return <Badge variant="secondary" className="bg-amber-500/10 text-amber-600 dark:text-amber-400 font-mono text-[10px]">KLTP</Badge>
    }
    return <Badge variant="secondary" className="bg-blue-500/10 text-blue-600 dark:text-blue-400 font-mono text-[10px]">TCP</Badge>
  }

  return (
    <div className="flex flex-1 flex-col gap-6 p-6">
      {/* 1. Top Summary Banner */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="shadow-2xs">
          <CardContent className="flex items-center justify-between p-4">
            <div className="flex flex-col gap-0.5">
              <span className="text-xs text-muted-foreground">全部连接</span>
              <span className="font-mono text-2xl font-bold">
                {stats.total}
              </span>
            </div>
            <div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
              <Network className="size-5" />
            </div>
          </CardContent>
        </Card>

        <Card className="shadow-2xs">
          <CardContent className="flex items-center justify-between p-4">
            <div className="flex flex-col gap-0.5">
              <span className="text-xs text-muted-foreground">已建立连接</span>
              <span className="font-mono text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                {stats.up}
              </span>
            </div>
            <div className="flex size-10 items-center justify-center rounded-xl bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
              <Plug className="size-5" />
            </div>
          </CardContent>
        </Card>

        <Card className="shadow-2xs">
          <CardContent className="flex items-center justify-between p-4">
            <div className="flex flex-col gap-0.5">
              <span className="text-xs text-muted-foreground">异常/重试中</span>
              <span className="font-mono text-2xl font-bold text-rose-500">
                {stats.down}
              </span>
            </div>
            <div className="flex size-10 items-center justify-center rounded-xl bg-rose-500/10 text-rose-500">
              <Unplug className="size-5" />
            </div>
          </CardContent>
        </Card>

        <Card className="shadow-2xs">
          <CardContent className="flex items-center justify-between p-4">
            <div className="flex flex-col gap-0.5">
              <span className="text-xs text-muted-foreground">
                实时吞吐
              </span>
              <div className="flex items-center gap-2 font-mono text-sm font-bold">
                <span className="text-rose-500">
                  ↑ {formatSpeed(stats.totalUpSpeed, 1)}
                </span>
                <span className="text-emerald-500">
                  ↓ {formatSpeed(stats.totalDownSpeed, 1)}
                </span>
              </div>
            </div>
            <div className="flex size-10 items-center justify-center rounded-xl bg-blue-500/10 text-blue-500">
              <ArrowUp className="size-5" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 2. Control Toolbar */}
      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div className="flex flex-1 flex-wrap items-center gap-2">
          {/* Search bar */}
          <div className="relative w-full max-w-xs">
            <Search className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="搜索 Socket / SID ..."
              className="pl-8"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>

          {/* Status filter toggle */}
          <div className="flex items-center rounded-lg border bg-background p-0.5 text-xs shadow-2xs">
            <button
              onClick={() => setStatusFilter("all")}
              className={`rounded-md px-2.5 py-1 font-medium transition-colors ${
                statusFilter === "all"
                  ? "bg-primary text-primary-foreground"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              全部 ({stats.total})
            </button>
            <button
              onClick={() => setStatusFilter("up")}
              className={`rounded-md px-2.5 py-1 font-medium transition-colors ${
                statusFilter === "up"
                  ? "bg-emerald-600 text-white"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              在线 ({stats.up})
            </button>
            <button
              onClick={() => setStatusFilter("down")}
              className={`rounded-md px-2.5 py-1 font-medium transition-colors ${
                statusFilter === "down"
                  ? "bg-rose-600 text-white"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              离线 ({stats.down})
            </button>
          </div>
        </div>

        {/* Action buttons & View mode switch */}
        <div className="flex items-center gap-2">
          <div className="flex items-center rounded-lg border bg-background p-0.5 shadow-2xs">
            <Button
              variant={viewMode === "grid" ? "secondary" : "ghost"}
              size="icon-xs"
              onClick={() => setViewMode("grid")}
              title="卡片网格视图"
            >
              <LayoutGrid className="size-3.5" />
            </Button>
            <Button
              variant={viewMode === "table" ? "secondary" : "ghost"}
              size="icon-xs"
              onClick={() => setViewMode("table")}
              title="表格视图"
            >
              <List className="size-3.5" />
            </Button>
          </div>

          {/* Add Connection Dialog */}
          <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
            <DialogTrigger
              render={
                <Button size="sm">
                  <Plus data-icon="inline-start" />
                  添加连接
                </Button>
              }
            />
            <DialogContent className="sm:max-w-md">
              <form onSubmit={handleAddSubmit}>
                <DialogHeader>
                  <DialogTitle>添加远程连接</DialogTitle>
                  <DialogDescription>
                    输入远端主机的 Socket 协议地址建立隧道
                  </DialogDescription>
                </DialogHeader>
                <div className="flex flex-col gap-4 py-4">
                  <div className="flex flex-col gap-2">
                    <label className="text-xs font-medium">
                      Socket 地址 URI
                    </label>
                    <Input
                      placeholder="tcp://... 或 udp://... 或 kltp://..."
                      value={newAddress}
                      onChange={(e) => setNewAddress(e.target.value)}
                      autoFocus
                    />
                    <span className="text-[11px] text-muted-foreground">
                      格式示例：<code>tcp://ip:port</code>、
                      <code>udp://ip:port</code>、<code>kltp://ip:port</code>
                    </span>
                  </div>
                  {addError && (
                    <div className="rounded-lg bg-destructive/10 p-2 text-xs text-destructive">
                      {addError}
                    </div>
                  )}
                </div>
                <DialogFooter>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setIsAddOpen(false)}
                  >
                    取消
                  </Button>
                  <Button type="submit" disabled={isSubmitting}>
                    {isSubmitting ? "添加中..." : "确认添加"}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* 3. Main Content: Grid or Table View */}
      {filteredLinks.length === 0 ? (
        <Card className="flex flex-col items-center justify-center p-12 text-center shadow-2xs">
          <div className="mb-3 flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
            <Network className="size-6" />
          </div>
          <CardTitle className="text-base font-semibold">
            未发现匹配的连接
          </CardTitle>
          <p className="mt-1 max-w-sm text-xs text-muted-foreground">
            当前没有满足条件的远程连接。您可以点击右上角的「添加连接」来新建与远端节点的链路。
          </p>
        </Card>
      ) : viewMode === "grid" ? (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
          {filteredLinks.map((link) => {
            const isUp =
              link.stateCode === 2 ||
              link.state.toLowerCase().includes("up") ||
              link.state === "ESTABLISHED"
            const isUnstable =
              link.stateCode === 1 ||
              link.state.toLowerCase().includes("unstable")

            return (
              <Card
                key={link.name}
                className="flex flex-col justify-between shadow-2xs transition-colors hover:border-primary/40"
              >
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex min-w-0 items-center gap-2">
                      <span
                        className={`size-2.5 shrink-0 rounded-full ${
                          isUp
                            ? "animate-pulse bg-emerald-500"
                            : isUnstable
                              ? "bg-amber-500"
                              : "bg-rose-500"
                        }`}
                      />
                      <div className="flex min-w-0 flex-col gap-0.5">
                        <div className="flex items-center gap-1.5">
                          {getProtocolBadge(link.socketAddress || link.name)}
                          <span
                            className="truncate font-mono text-sm font-semibold text-foreground"
                            title={link.socketAddress || link.name}
                          >
                            {link.socketAddress || link.name}
                          </span>
                        </div>
                      </div>
                    </div>

                    {/* Actions dropdown component */}
                    <ConnectionActionMenu
                      link={link}
                      onLinkAction={onLinkAction}
                      onRemoveLink={onRemoveLink}
                      onCopyText={copyText}
                    />
                  </div>
                </CardHeader>

                <CardContent className="flex flex-col gap-3.5 text-xs">
                  {/* Remote Virtual IPv6 Address */}
                  <div className="flex items-center justify-between gap-1.5 rounded-lg border bg-background/60 px-2.5 py-1.5">
                    <div className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
                      <ChevronsLeftRightEllipsis className="size-3.5 shrink-0" />
                      <span className="truncate">远端 SID:</span>
                    </div>
                    {link.vaddr ? (
                      <div className="flex items-center gap-1">
                        <span
                          className="max-w-[170px] truncate font-mono font-medium text-foreground"
                          title={link.vaddr}
                        >
                          {link.vaddr}
                        </span>
                        <Button
                          variant="ghost"
                          size="icon-xs"
                          className="size-4"
                          onClick={() => copyText(link.vaddr!)}
                        >
                          {copiedAddress === link.vaddr ? (
                            <Check className="size-3 text-emerald-500" />
                          ) : (
                            <Copy className="size-3" />
                          )}
                        </Button>
                      </div>
                    ) : (
                      <span className="text-muted-foreground italic">
                        未协商
                      </span>
                    )}
                  </div>

                  {/* Realtime Throughput & PPS */}
                  <div className="grid grid-cols-2 gap-2">
                    <div className="flex flex-col gap-0.5 rounded-lg border bg-card p-2">
                      <div className="flex items-center justify-between text-[11px] text-muted-foreground">
                        <span className="flex items-center gap-1 text-rose-500">
                          <ArrowUp className="size-3" /> 发送
                        </span>
                        <span>{formatPPS(link.upPPS)}</span>
                      </div>
                      <span className="font-mono text-sm font-bold text-foreground">
                        {formatSpeed(link.upSpeed)}
                      </span>
                    </div>

                    <div className="flex flex-col gap-0.5 rounded-lg border bg-card p-2">
                      <div className="flex items-center justify-between text-[11px] text-muted-foreground">
                        <span className="flex items-center gap-1 text-emerald-500">
                          <ArrowDown className="size-3" /> 接收
                        </span>
                        <span>{formatPPS(link.downPPS)}</span>
                      </div>
                      <span className="font-mono text-sm font-bold text-foreground">
                        {formatSpeed(link.downSpeed)}
                      </span>
                    </div>
                  </div>

                  {/* Delay & Jitter */}
                  <div className="flex flex-col gap-1 rounded-lg border bg-muted/30 p-2 text-[11px] text-muted-foreground">
                    <div className="flex items-center justify-between">
                      <span>单向时延 (上/下):</span>
                      <span className="font-mono font-semibold text-foreground">
                        {isUp
                          ? `${formatNanoDelay(link.upDelay)} / ${formatNanoDelay(link.downDelay)}`
                          : "NaN / NaN"}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span>网络抖动 (Jitter):</span>
                      <span className="font-mono text-foreground">
                        {isUp ? formatNanoDelay(link.upJitter) : "NaN"}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span>累计流量 (发/收):</span>
                      <span className="font-mono text-foreground">
                        {formatBytes(link.upTraffic, 1)} /{" "}
                        {formatBytes(link.downTraffic, 1)}
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>
      ) : (
        /* Table View */
        <Card className="overflow-hidden shadow-2xs">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-12 text-center">状态</TableHead>
                <TableHead>Socket 地址</TableHead>
                <TableHead>远端 SID (IPv6)</TableHead>
                <TableHead className="text-right">实时发送 (↑)</TableHead>
                <TableHead className="text-right">实时接收 (↓)</TableHead>
                <TableHead className="text-right">单向时延</TableHead>
                <TableHead className="text-right">累计总流量</TableHead>
                <TableHead className="w-24 text-center">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredLinks.map((link) => {
                const isUp =
                  link.stateCode === 2 ||
                  link.state.toLowerCase().includes("up") ||
                  link.state === "ESTABLISHED"
                return (
                  <TableRow key={link.name}>
                    <TableCell className="text-center">
                      <span
                        className={`inline-block size-2 rounded-full ${
                          isUp ? "bg-emerald-500" : "bg-rose-500"
                        }`}
                        title={link.state}
                      />
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1.5 font-mono text-xs font-semibold">
                        {getProtocolBadge(link.socketAddress || link.name)}
                        <span>{link.socketAddress || link.name}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="font-mono text-xs text-muted-foreground">
                        {link.vaddr || "--"}
                      </span>
                    </TableCell>
                    <TableCell className="text-right font-mono text-xs">
                      <span className="font-semibold text-rose-500">
                        {formatSpeed(link.upSpeed)}
                      </span>
                      <span className="ml-1 text-[10px] text-muted-foreground">
                        ({formatPPS(link.upPPS)})
                      </span>
                    </TableCell>
                    <TableCell className="text-right font-mono text-xs">
                      <span className="font-semibold text-emerald-500">
                        {formatSpeed(link.downSpeed)}
                      </span>
                      <span className="ml-1 text-[10px] text-muted-foreground">
                        ({formatPPS(link.downPPS)})
                      </span>
                    </TableCell>
                    <TableCell className="text-right font-mono text-xs">
                      {isUp ? formatNanoDelay(link.upDelay) : "NaN"}
                    </TableCell>
                    <TableCell className="text-right font-mono text-xs text-muted-foreground">
                      {formatBytes(
                        (link.upTraffic || 0) + (link.downTraffic || 0)
                      )}
                    </TableCell>
                    <TableCell className="text-center">
                      <ConnectionActionMenu
                        link={link}
                        onLinkAction={onLinkAction}
                        onRemoveLink={onRemoveLink}
                        onCopyText={copyText}
                      />
                    </TableCell>
                  </TableRow>
                )
              })}
            </TableBody>
          </Table>
        </Card>
      )}
    </div>
  )
}
