'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Cpu,
  Search,
  RefreshCcw,
  Loader2,
  Wifi,
  WifiOff,
  AlertTriangle,
  Settings,
  UserMinus,
  UserPlus,
  Eye,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  X,
  Thermometer,
  Clock,
  Server,
  User,
  Signal,
  Activity,
} from 'lucide-react'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'

// ---- Types ----
interface ONU {
  id: string
  oltId: string
  serialNumber: string
  slot: number
  port: number
  userId: string | null
  status: string
  signalStrength: number
  temperature: number
  uptime: number
  lastSeen: string
  createdAt: string
  updatedAt: string
  olt: {
    id: string
    name: string
    ipAddress: string
    status: string
  } | null
  user: {
    id: string
    name: string
    email: string
    status: string
  } | null
}

interface OLTDevice {
  id: string
  name: string
  ipAddress: string
  status: string
}

interface ONUResponse {
  onus: ONU[]
  statusCounts: Array<{ status: string; count: number }>
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

interface ONUDetailResponse extends ONU {
  user: {
    id: string
    name: string
    email: string
    phone: string
    status: string
    area: { id: string; name: string } | null
  } | null
}

// ---- Helpers ----
function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

function formatDateTime(dateStr: string): string {
  return new Date(dateStr).toLocaleString('en-US', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function formatUptime(seconds: number): string {
  if (seconds <= 0) return 'N/A'
  const d = Math.floor(seconds / 86400)
  const h = Math.floor((seconds % 86400) / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  if (d > 0) return `${d}d ${h}h`
  if (h > 0) return `${h}h ${m}m`
  return `${m}m`
}

function formatTimeAgo(dateStr: string): string {
  const now = Date.now()
  const then = new Date(dateStr).getTime()
  const diffMs = now - then
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)
  if (diffMins < 1) return 'Just now'
  if (diffMins < 60) return `${diffMins}m ago`
  if (diffHours < 24) return `${diffHours}h ago`
  if (diffDays < 30) return `${diffDays}d ago`
  return formatDate(dateStr)
}

// ---- Status Colors ----
const onuStatusColor: Record<string, string> = {
  ONLINE: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  OFFLINE: 'bg-gray-100 text-gray-600 dark:bg-gray-800/30 dark:text-gray-400',
  PROVISIONING: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  FAULTY: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
}

// ---- Signal Strength Visual ----
function SignalBar({ value }: { value: number }) {
  // Signal strength: green (> -20dBm), yellow (-20 to -25dBm), red (< -25dBm)
  let color = 'bg-emerald-500'
  let label = 'Good'
  if (value < -25) {
    color = 'bg-red-500'
    label = 'Weak'
  } else if (value <= -20) {
    color = 'bg-amber-500'
    label = 'Fair'
  }

  // Map to percentage: -40 is worst, -10 is best
  const percentage = Math.max(0, Math.min(100, ((value + 40) / 30) * 100))

  return (
    <div className="flex items-center gap-2">
      <div className="w-16 md:w-20 h-2 bg-muted rounded-full overflow-hidden">
        <div className={`h-full rounded-full transition-all ${color}`} style={{ width: `${percentage}%` }} />
      </div>
      <span className="text-xs font-mono text-muted-foreground whitespace-nowrap">
        {value} dBm
      </span>
    </div>
  )
}

// ---- Signal Strength Gauge ----
function SignalGauge({ value }: { value: number }) {
  let color = 'text-emerald-500'
  let bgColor = 'bg-emerald-100 dark:bg-emerald-900/30'
  let label = 'Good'
  let labelColor = 'text-emerald-600 dark:text-emerald-400'
  if (value < -25) {
    color = 'text-red-500'
    bgColor = 'bg-red-100 dark:bg-red-900/30'
    label = 'Weak'
    labelColor = 'text-red-600 dark:text-red-400'
  } else if (value <= -20) {
    color = 'text-amber-500'
    bgColor = 'bg-amber-100 dark:bg-amber-900/30'
    label = 'Fair'
    labelColor = 'text-amber-600 dark:text-amber-400'
  }

  const percentage = Math.max(0, Math.min(100, ((value + 40) / 30) * 100))

  return (
    <div className="flex flex-col items-center gap-2">
      <div className={`relative w-24 h-24 rounded-full flex items-center justify-center ${bgColor}`}>
        <svg className="absolute inset-0 w-full h-full -rotate-90" viewBox="0 0 100 100">
          <circle
            cx="50" cy="50" r="42"
            fill="none"
            stroke="currentColor"
            strokeWidth="6"
            className="text-muted/30"
          />
          <circle
            cx="50" cy="50" r="42"
            fill="none"
            stroke="currentColor"
            strokeWidth="6"
            strokeLinecap="round"
            strokeDasharray={`${(percentage / 100) * 264} 264`}
            className={color}
          />
        </svg>
        <div className="text-center z-10">
          <p className="text-lg font-bold">{value}</p>
          <p className="text-[10px] text-muted-foreground">dBm</p>
        </div>
      </div>
      <Badge variant="secondary" className={`${labelColor} ${bgColor}`}>
        {label}
      </Badge>
    </div>
  )
}

// ---- Summary Card ----
function SummaryCard({
  title,
  value,
  icon: Icon,
  color,
}: {
  title: string
  value: number
  icon: React.ElementType
  color: string
}) {
  return (
    <Card className="gap-0">
      <CardContent className="p-4 md:p-6">
        <div className="flex items-center gap-4">
          <div className={`flex items-center justify-center size-10 md:size-12 rounded-xl ${color}`}>
            <Icon className="size-5 md:size-6 text-white" />
          </div>
          <div>
            <p className="text-sm text-muted-foreground">{title}</p>
            <p className="text-2xl md:text-3xl font-bold tracking-tight">{value}</p>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}

// ---- Pagination Component ----
function Pagination({
  page,
  totalPages,
  onPageChange,
}: {
  page: number
  totalPages: number
  onPageChange: (page: number) => void
}) {
  if (totalPages <= 1) return null
  return (
    <div className="flex items-center justify-between gap-4 pt-4">
      <p className="text-sm text-muted-foreground">
        Page {page} of {totalPages}
      </p>
      <div className="flex items-center gap-1">
        <Button variant="outline" size="icon" className="size-8" onClick={() => onPageChange(1)} disabled={page <= 1}>
          <ChevronsLeft className="size-4" />
        </Button>
        <Button variant="outline" size="icon" className="size-8" onClick={() => onPageChange(page - 1)} disabled={page <= 1}>
          <ChevronLeft className="size-4" />
        </Button>
        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
          let pageNum: number
          if (totalPages <= 5) pageNum = i + 1
          else if (page <= 3) pageNum = i + 1
          else if (page >= totalPages - 2) pageNum = totalPages - 4 + i
          else pageNum = page - 2 + i
          return (
            <Button key={pageNum} variant={pageNum === page ? 'default' : 'outline'} size="icon" className="size-8" onClick={() => onPageChange(pageNum)}>
              {pageNum}
            </Button>
          )
        })}
        <Button variant="outline" size="icon" className="size-8" onClick={() => onPageChange(page + 1)} disabled={page >= totalPages}>
          <ChevronRight className="size-4" />
        </Button>
        <Button variant="outline" size="icon" className="size-8" onClick={() => onPageChange(totalPages)} disabled={page >= totalPages}>
          <ChevronsRight className="size-4" />
        </Button>
      </div>
    </div>
  )
}

// ---- Table Skeleton ----
function TableSkeleton() {
  return (
    <div className="space-y-3 p-4">
      <Skeleton className="h-10 w-full" />
      {Array.from({ length: 6 }).map((_, i) => (
        <Skeleton key={i} className="h-12 w-full" />
      ))}
    </div>
  )
}

// ---- Main Component ----
export default function ONUView() {
  const { toast } = useToast()

  // Data state
  const [onus, setOnus] = useState<ONU[]>([])
  const [total, setTotal] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Summary stats
  const [stats, setStats] = useState({
    total: 0,
    online: 0,
    offline: 0,
    faulty: 0,
  })

  // Filter state
  const [searchQuery, setSearchQuery] = useState('')
  const [searchInput, setSearchInput] = useState('')
  const [statusFilter, setStatusFilter] = useState('ALL')
  const [oltFilter, setOltFilter] = useState('')
  const [page, setPage] = useState(1)
  const [perPage, setPerPage] = useState(20)

  // Reference data
  const [olts, setOlts] = useState<OLTDevice[]>([])

  // Detail dialog
  const [detailOpen, setDetailOpen] = useState(false)
  const [detailData, setDetailData] = useState<ONUDetailResponse | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)

  // Assign dialog
  const [assignOpen, setAssignOpen] = useState(false)
  const [assignOnu, setAssignOnu] = useState<ONU | null>(null)
  const [assignUserId, setAssignUserId] = useState('')
  const [assigning, setAssigning] = useState(false)

  // Fetch OLTs for filter
  const fetchOlts = useCallback(async () => {
    const res = await api.get<{ data: { olts: OLTDevice[] } }>('/api/olt', { limit: 100 })
    if (res.success && res.data) {
      setOlts(res.data.data.olts)
    }
  }, [])

  useEffect(() => {
    fetchOlts()
  }, [fetchOlts])

  // Fetch ONUs
  const fetchOnus = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await api.get<{ data: ONUResponse }>('/api/onu', {
        status: statusFilter === 'ALL' ? undefined : statusFilter,
        oltId: oltFilter || undefined,
        search: searchQuery || undefined,
        page,
        limit: perPage,
      })

      if (res.success && res.data) {
        setOnus(res.data.data.onus)
        setTotal(res.data.data.pagination.total)
        setTotalPages(res.data.data.pagination.totalPages)

        // Status counts from response
        const counts = res.data.data.statusCounts
        const statsMap: Record<string, number> = {}
        counts.forEach((c) => {
          statsMap[c.status] = c.count
        })
        setStats({
          total: res.data.data.pagination.total,
          online: statsMap['ONLINE'] || 0,
          offline: statsMap['OFFLINE'] || 0,
          faulty: statsMap['FAULTY'] || 0,
        })
      } else {
        setError(res.error || 'Failed to load ONUs')
      }
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [statusFilter, oltFilter, searchQuery, page, perPage])

  useEffect(() => {
    fetchOnus()
  }, [fetchOnus])

  // Reset page on filter change
  useEffect(() => {
    setPage(1)
  }, [statusFilter, oltFilter, searchQuery, perPage])

  // Debounced search
  useEffect(() => {
    const timeout = setTimeout(() => setSearchQuery(searchInput), 400)
    return () => clearTimeout(timeout)
  }, [searchInput])

  // Handle view detail
  const handleViewDetail = async (onu: ONU) => {
    setDetailOpen(true)
    setDetailLoading(true)
    try {
      const res = await api.get<{ data: ONUDetailResponse }>(`/api/onu/${onu.id}`)
      if (res.success && res.data) {
        setDetailData(res.data.data)
      } else {
        setDetailData(onu as unknown as ONUDetailResponse)
      }
    } catch {
      setDetailData(onu as unknown as ONUDetailResponse)
    } finally {
      setDetailLoading(false)
    }
  }

  // Handle assign/unassign
  const handleOpenAssign = (onu: ONU) => {
    setAssignOnu(onu)
    setAssignUserId('')
    setAssignOpen(true)
  }

  const handleAssign = async () => {
    if (!assignOnu) return
    try {
      setAssigning(true)
      const res = await api.put(`/api/onu/${assignOnu.id}`, {
        userId: assignUserId || null,
      })
      if (res.success) {
        toast({ title: 'Success', description: assignUserId ? 'Client assigned successfully' : 'Client unassigned successfully' })
        setAssignOpen(false)
        fetchOnus()
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to update ONU', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Network error', variant: 'destructive' })
    } finally {
      setAssigning(false)
    }
  }

  const handleUnassign = (onu: ONU) => {
    setAssignOnu(onu)
    setAssignUserId('')
    setAssignOpen(true)
  }

  return (
    <div className="space-y-4 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold tracking-tight">ONU Management</h1>
          <p className="text-muted-foreground mt-1">
            Monitor and manage Optical Network Units
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchOnus}>
          <RefreshCcw className="size-4" />
          <span className="hidden sm:inline">Refresh</span>
        </Button>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <SummaryCard title="Total ONUs" value={stats.total} icon={Cpu} color="bg-slate-600" />
        <SummaryCard title="Online" value={stats.online} icon={Wifi} color="bg-emerald-600" />
        <SummaryCard title="Offline" value={stats.offline} icon={WifiOff} color="bg-gray-500" />
        <SummaryCard title="Faulty" value={stats.faulty} icon={AlertTriangle} color="bg-red-600" />
      </div>

      {/* Filter Bar */}
      <Card className="p-4">
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              placeholder="Search by serial number..."
              className="pl-9"
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
            />
            {searchInput && (
              <Button variant="ghost" size="icon" className="absolute right-1 top-1/2 -translate-y-1/2 size-7" onClick={() => setSearchInput('')}>
                <X className="size-3" />
              </Button>
            )}
          </div>
          <div className="flex flex-wrap gap-2">
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[140px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">All Status</SelectItem>
                <SelectItem value="ONLINE">Online</SelectItem>
                <SelectItem value="OFFLINE">Offline</SelectItem>
                <SelectItem value="PROVISIONING">Provisioning</SelectItem>
                <SelectItem value="FAULTY">Faulty</SelectItem>
              </SelectContent>
            </Select>
            <Select value={oltFilter || '__all__'} onValueChange={(v) => setOltFilter(v === '__all__' ? '' : v)}>
              <SelectTrigger className="w-[160px]">
                <SelectValue placeholder="All OLTs" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="__all__">All OLTs</SelectItem>
                {olts.map((olt) => (
                  <SelectItem key={olt.id} value={olt.id}>
                    {olt.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={String(perPage)} onValueChange={(v) => setPerPage(Number(v))}>
              <SelectTrigger className="w-[100px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="20">20</SelectItem>
                <SelectItem value="50">50</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </Card>

      {/* Data Table */}
      <Card>
        <CardContent className="p-0">
          {error ? (
            <div className="flex flex-col items-center justify-center py-16 gap-4">
              <AlertTriangle className="size-12 text-destructive" />
              <p className="text-muted-foreground text-center">{error}</p>
              <Button onClick={fetchOnus} variant="outline">Retry</Button>
            </div>
          ) : loading ? (
            <TableSkeleton />
          ) : (
            <div>
              <div className="flex items-center justify-between px-4 py-3 border-b">
                <p className="text-sm text-muted-foreground">
                  Showing {onus.length} of {total} ONUs
                </p>
              </div>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Serial Number</TableHead>
                      <TableHead className="hidden md:table-cell">OLT Device</TableHead>
                      <TableHead className="hidden lg:table-cell">Slot/Port</TableHead>
                      <TableHead className="hidden md:table-cell">Client</TableHead>
                      <TableHead className="hidden xl:table-cell min-w-[140px]">Signal</TableHead>
                      <TableHead className="hidden lg:table-cell">Temp</TableHead>
                      <TableHead className="hidden md:table-cell">Uptime</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="hidden lg:table-cell">Last Seen</TableHead>
                      <TableHead className="w-24 text-right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {onus.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={10} className="h-32 text-center">
                          <div className="flex flex-col items-center gap-2">
                            <Cpu className="size-8 text-muted-foreground opacity-50" />
                            <p className="text-muted-foreground text-sm">No ONUs found</p>
                          </div>
                        </TableCell>
                      </TableRow>
                    ) : (
                      onus.map((onu) => (
                        <TableRow key={onu.id}>
                          <TableCell>
                            <span className="font-mono text-sm font-medium">{onu.serialNumber}</span>
                          </TableCell>
                          <TableCell className="hidden md:table-cell">
                            <div className="flex items-center gap-2">
                              <Server className="size-3.5 text-muted-foreground" />
                              <span className="text-sm">{onu.olt?.name || 'N/A'}</span>
                            </div>
                          </TableCell>
                          <TableCell className="hidden lg:table-cell">
                            <Badge variant="outline" className="font-mono text-xs">
                              {onu.slot}/{onu.port}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden md:table-cell">
                            {onu.user ? (
                              <span className="text-sm">{onu.user.name}</span>
                            ) : (
                              <span className="text-sm text-muted-foreground">Unassigned</span>
                            )}
                          </TableCell>
                          <TableCell className="hidden xl:table-cell">
                            <SignalBar value={onu.signalStrength} />
                          </TableCell>
                          <TableCell className="hidden lg:table-cell">
                            <div className="flex items-center gap-1">
                              <Thermometer className="size-3 text-muted-foreground" />
                              <span className="text-sm">{onu.temperature}°C</span>
                            </div>
                          </TableCell>
                          <TableCell className="hidden md:table-cell text-sm text-muted-foreground">
                            {formatUptime(onu.uptime)}
                          </TableCell>
                          <TableCell>
                            <Badge variant="secondary" className={onuStatusColor[onu.status] || ''}>
                              {onu.status}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden lg:table-cell text-sm text-muted-foreground">
                            {formatTimeAgo(onu.lastSeen)}
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex items-center justify-end gap-1">
                              <Button variant="ghost" size="icon" className="size-8" onClick={() => handleViewDetail(onu)}>
                                <Eye className="size-4" />
                              </Button>
                              {onu.user ? (
                                <Button variant="ghost" size="icon" className="size-8" onClick={() => handleUnassign(onu)} title="Unassign client">
                                  <UserMinus className="size-4 text-orange-500" />
                                </Button>
                              ) : (
                                <Button variant="ghost" size="icon" className="size-8" onClick={() => handleOpenAssign(onu)} title="Assign client">
                                  <UserPlus className="size-4 text-emerald-500" />
                                </Button>
                              )}
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="px-4 pb-4">
                <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* ONU Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-2xl max-h-[90vh] p-0 gap-0">
          <ScrollArea className="max-h-[90vh]">
            <div className="p-6 space-y-6">
              <DialogHeader>
                <div className="flex items-center gap-3">
                  <div className="flex items-center justify-center size-12 rounded-xl bg-slate-100 dark:bg-slate-800">
                    <Cpu className="size-6 text-slate-600 dark:text-slate-400" />
                  </div>
                  <div className="min-w-0">
                    <DialogTitle className="text-lg">ONU Detail</DialogTitle>
                    <DialogDescription className="flex items-center gap-2 mt-1">
                      <Badge variant="secondary" className={onuStatusColor[detailData?.status || '']}>
                        {detailData?.status || 'N/A'}
                      </Badge>
                      <span className="font-mono text-xs">{detailData?.serialNumber}</span>
                    </DialogDescription>
                  </div>
                </div>
              </DialogHeader>

              {detailLoading ? (
                <div className="space-y-4">
                  <Skeleton className="h-32 w-full rounded-xl" />
                  <Skeleton className="h-20 w-full rounded-xl" />
                </div>
              ) : detailData ? (
                <>
                  <Separator />

                  {/* Signal Strength Gauge */}
                  <div className="flex justify-center">
                    <SignalGauge value={detailData.signalStrength} />
                  </div>

                  {/* Device Info */}
                  <div>
                    <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <Activity className="size-4" />
                      Device Information
                    </h4>
                    <div className="grid grid-cols-2 gap-3">
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Serial Number</p>
                        <p className="text-sm font-mono font-medium mt-0.5">{detailData.serialNumber}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Slot / Port</p>
                        <p className="text-sm font-mono font-medium mt-0.5">{detailData.slot} / {detailData.port}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Temperature</p>
                        <p className="text-sm font-medium mt-0.5 flex items-center gap-1">
                          <Thermometer className="size-3.5" />
                          {detailData.temperature}°C
                        </p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Uptime</p>
                        <p className="text-sm font-medium mt-0.5 flex items-center gap-1">
                          <Clock className="size-3.5" />
                          {formatUptime(detailData.uptime)}
                        </p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Last Seen</p>
                        <p className="text-sm font-medium mt-0.5">{formatDateTime(detailData.lastSeen)}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Registered</p>
                        <p className="text-sm font-medium mt-0.5">{formatDate(detailData.createdAt)}</p>
                      </div>
                    </div>
                  </div>

                  <Separator />

                  {/* OLT Info */}
                  <div>
                    <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <Server className="size-4" />
                      OLT Device
                    </h4>
                    {detailData.olt ? (
                      <div className="rounded-lg border p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm font-medium">{detailData.olt.name}</span>
                          <Badge variant="secondary" className={onuStatusColor[detailData.olt.status] || ''}>
                            {detailData.olt.status}
                          </Badge>
                        </div>
                        <p className="text-xs text-muted-foreground">IP: {detailData.olt.ipAddress}</p>
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground">No OLT device assigned</p>
                    )}
                  </div>

                  <Separator />

                  {/* Client Info */}
                  <div>
                    <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <User className="size-4" />
                      Assigned Client
                    </h4>
                    {detailData.user ? (
                      <div className="rounded-lg border p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm font-medium">{detailData.user.name}</span>
                          <Badge variant="secondary" className={onuStatusColor[detailData.user.status] || ''}>
                            {detailData.user.status}
                          </Badge>
                        </div>
                        <p className="text-xs text-muted-foreground">{detailData.user.email}</p>
                        {'phone' in detailData.user && (
                          <p className="text-xs text-muted-foreground">{(detailData.user as { phone?: string }).phone || ''}</p>
                        )}
                        {'area' in detailData.user && detailData.user.area && (
                          <p className="text-xs text-muted-foreground">
                            Area: {(detailData.user as { area: { id: string; name: string } | null }).area?.name}
                          </p>
                        )}
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground">No client assigned to this ONU</p>
                    )}
                  </div>
                </>
              ) : null}
            </div>
          </ScrollArea>
        </DialogContent>
      </Dialog>

      {/* Assign/Unassign Client Dialog */}
      <Dialog open={assignOpen} onOpenChange={setAssignOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>
              {assignOnu?.userId ? 'Unassign Client' : 'Assign Client'}
            </DialogTitle>
            <DialogDescription>
              {assignOnu?.userId
                ? `Remove client from ONU ${assignOnu?.serialNumber}?`
                : `Assign a client to ONU ${assignOnu?.serialNumber}`}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {!assignOnu?.userId && (
              <div>
                <Label>Client User ID</Label>
                <Input
                  className="mt-1.5"
                  placeholder="Enter user ID..."
                  value={assignUserId}
                  onChange={(e) => setAssignUserId(e.target.value)}
                />
              </div>
            )}
            {assignOnu?.userId && (
              <div className="rounded-lg bg-muted/50 p-3">
                <p className="text-sm">Currently assigned to: <strong>{assignOnu.user?.name}</strong></p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAssignOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleAssign} disabled={assigning || (!assignOnu?.userId && !assignUserId)}>
              {assigning ? <Loader2 className="size-4 animate-spin" /> : null}
              {assignOnu?.userId ? 'Unassign' : 'Assign'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
