'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Server,
  Plus,
  Search,
  Pencil,
  Trash2,
  RefreshCcw,
  Loader2,
  Wifi,
  WifiOff,
  Cpu,
  EthernetPort,
  Eye,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  X,
  AlertTriangle,
  Activity,
  Monitor,
} 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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-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 OLTDevice {
  id: string
  name: string
  ipAddress: string
  username: string
  password: string
  model: string
  firmware: string
  portCount: number
  status: string
  createdAt: string
  updatedAt: string
  _count: {
    onus: number
    onusOnline: number
  }
}

interface OLTResponse {
  olts: OLTDevice[]
  pagination: {
    page: number
    limit: number
    total: number
    totalPages: number
  }
}

interface ConnectedONU {
  id: string
  serialNumber: string
  slot: number
  port: number
  status: string
  signalStrength: number
  user: {
    id: string
    name: string
    email: string
    status: string
  } | null
}

interface OLTDetailResponse extends OLTDevice {
  onus: ConnectedONU[]
  onuStatusCounts: {
    online: number
    offline: number
    provisioning: number
    faulty: number
  }
}

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

// ---- Status Colors ----
const oltStatusColor: Record<string, string> = {
  ONLINE: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  OFFLINE: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
}

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',
}

// ---- 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>
  )
}

// ---- Default form ----
const defaultForm = {
  name: '',
  ipAddress: '',
  username: '',
  password: '',
  model: '',
  firmware: '',
  portCount: '16',
}

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

  // Data state
  const [olts, setOlts] = useState<OLTDevice[]>([])
  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,
    totalOnus: 0,
    totalPorts: 0,
  })

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

  // Add/Edit dialog
  const [formOpen, setFormOpen] = useState(false)
  const [editingOLT, setEditingOLT] = useState<OLTDevice | null>(null)
  const [form, setForm] = useState(defaultForm)
  const [submitting, setSubmitting] = useState(false)

  // Delete dialog
  const [deleteTarget, setDeleteTarget] = useState<OLTDevice | null>(null)
  const [deleting, setDeleting] = useState(false)

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

  // Fetch OLTs
  const fetchOLTs = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await api.get<{ data: OLTResponse }>('/api/olt', {
        search: searchQuery || undefined,
        status: statusFilter === 'ALL' ? undefined : statusFilter,
        page,
        limit: perPage,
      })

      if (res.success && res.data) {
        setOlts(res.data.data.olts)
        setTotal(res.data.data.pagination.total)
        setTotalPages(res.data.data.pagination.totalPages)

        // Compute stats
        const allOlts = res.data.data.olts
        const onlineCount = allOlts.filter((o) => o.status === 'ONLINE').length
        const totalOnus = allOlts.reduce((s, o) => s + o._count.onus, 0)
        const totalPorts = allOlts.reduce((s, o) => s + o.portCount, 0)

        if (page === 1 && res.data.data.pagination.total <= perPage) {
          setStats({
            total: res.data.data.pagination.total,
            online: onlineCount,
            totalOnus,
            totalPorts,
          })
        } else {
          // Fetch all for accurate summary
          const summaryRes = await api.get<{ data: OLTResponse }>('/api/olt', { limit: 500 })
          if (summaryRes.success && summaryRes.data) {
            const all = summaryRes.data.data.olts
            setStats({
              total: summaryRes.data.data.pagination.total,
              online: all.filter((o) => o.status === 'ONLINE').length,
              totalOnus: all.reduce((s, o) => s + o._count.onus, 0),
              totalPorts: all.reduce((s, o) => s + o.portCount, 0),
            })
          }
        }
      } else {
        setError(res.error || 'Failed to load OLT devices')
      }
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [searchQuery, statusFilter, page, perPage])

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

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

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

  // Handlers
  const handleOpenAdd = () => {
    setEditingOLT(null)
    setForm(defaultForm)
    setFormOpen(true)
  }

  const handleOpenEdit = (olt: OLTDevice) => {
    setEditingOLT(olt)
    setForm({
      name: olt.name,
      ipAddress: olt.ipAddress,
      username: olt.username,
      password: '',
      model: olt.model,
      firmware: olt.firmware,
      portCount: String(olt.portCount),
    })
    setFormOpen(true)
  }

  const handleSubmit = async () => {
    if (!form.name.trim() || !form.ipAddress.trim()) {
      toast({
        title: 'Validation Error',
        description: 'Name and IP address are required',
        variant: 'destructive',
      })
      return
    }

    try {
      setSubmitting(true)
      const body = {
        name: form.name,
        ipAddress: form.ipAddress,
        username: form.username,
        password: form.password || undefined,
        model: form.model,
        firmware: form.firmware,
        portCount: parseInt(form.portCount) || 16,
      }

      if (editingOLT) {
        const res = await api.put(`/api/olt/${editingOLT.id}`, body)
        if (res.success) {
          toast({ title: 'Success', description: 'OLT device updated successfully' })
          setFormOpen(false)
          fetchOLTs()
        } else {
          toast({ title: 'Error', description: res.error || 'Failed to update OLT', variant: 'destructive' })
        }
      } else {
        const res = await api.post('/api/olt', { ...body, status: 'ONLINE' })
        if (res.success) {
          toast({ title: 'Success', description: 'OLT device created successfully' })
          setFormOpen(false)
          fetchOLTs()
        } else {
          toast({ title: 'Error', description: res.error || 'Failed to create OLT', variant: 'destructive' })
        }
      }
    } catch {
      toast({ title: 'Error', description: 'Network error', variant: 'destructive' })
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async () => {
    if (!deleteTarget) return
    try {
      setDeleting(true)
      const res = await api.del(`/api/olt/${deleteTarget.id}`)
      if (res.success) {
        toast({ title: 'Success', description: 'OLT device deleted successfully' })
        setDeleteTarget(null)
        fetchOLTs()
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to delete OLT', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Network error', variant: 'destructive' })
    } finally {
      setDeleting(false)
    }
  }

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

  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">OLT Management</h1>
          <p className="text-muted-foreground mt-1">
            Manage Optical Line Terminal devices
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={fetchOLTs}>
            <RefreshCcw className="size-4" />
            <span className="hidden sm:inline">Refresh</span>
          </Button>
          <Button size="sm" onClick={handleOpenAdd}>
            <Plus className="size-4" />
            Add OLT
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <SummaryCard title="Total OLTs" value={stats.total} icon={Server} color="bg-slate-600" />
        <SummaryCard title="Online" value={stats.online} icon={Wifi} color="bg-emerald-600" />
        <SummaryCard title="ONUs Connected" value={stats.totalOnus} icon={Cpu} color="bg-sky-600" />
        <SummaryCard title="Total Ports" value={stats.totalPorts} icon={Ethernet} color="bg-violet-600" />
      </div>

      {/* Search & 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 name, IP, or model..."
              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-[130px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">All Status</SelectItem>
                <SelectItem value="ONLINE">Online</SelectItem>
                <SelectItem value="OFFLINE">Offline</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={fetchOLTs} 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 {olts.length} of {total} OLT devices
                </p>
              </div>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>IP Address</TableHead>
                      <TableHead className="hidden md:table-cell">Model</TableHead>
                      <TableHead className="hidden lg:table-cell">Firmware</TableHead>
                      <TableHead className="hidden sm:table-cell text-center">Ports</TableHead>
                      <TableHead className="hidden md:table-cell text-center">Online ONUs</TableHead>
                      <TableHead className="hidden sm:table-cell text-center">Total ONUs</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead className="w-24 text-right">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {olts.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={9} className="h-32 text-center">
                          <div className="flex flex-col items-center gap-2">
                            <Server className="size-8 text-muted-foreground opacity-50" />
                            <p className="text-muted-foreground text-sm">No OLT devices found</p>
                          </div>
                        </TableCell>
                      </TableRow>
                    ) : (
                      olts.map((olt) => (
                        <TableRow key={olt.id}>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <div className="flex items-center justify-center size-8 rounded-lg bg-slate-100 dark:bg-slate-800">
                                <Server className="size-4 text-slate-600 dark:text-slate-400" />
                              </div>
                              <span className="font-medium">{olt.name}</span>
                            </div>
                          </TableCell>
                          <TableCell>
                            <span className="font-mono text-sm">{olt.ipAddress}</span>
                          </TableCell>
                          <TableCell className="hidden md:table-cell">
                            <span className="text-sm text-muted-foreground">{olt.model || '—'}</span>
                          </TableCell>
                          <TableCell className="hidden lg:table-cell">
                            <span className="text-sm text-muted-foreground">{olt.firmware || '—'}</span>
                          </TableCell>
                          <TableCell className="hidden sm:table-cell text-center">
                            <div className="flex items-center justify-center gap-1">
                              <EthernetPort className="size-3.5 text-muted-foreground" />
                              <span className="text-sm font-medium">{olt.portCount}</span>
                            </div>
                          </TableCell>
                          <TableCell className="hidden md:table-cell text-center">
                            <Badge variant="secondary" className="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400">
                              {olt._count.onusOnline}
                            </Badge>
                          </TableCell>
                          <TableCell className="hidden sm:table-cell text-center">
                            <Badge variant="secondary">
                              {olt._count.onus}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge variant="secondary" className={oltStatusColor[olt.status] || ''}>
                              {olt.status}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex items-center justify-end gap-1">
                              <Button variant="ghost" size="icon" className="size-8" onClick={() => handleViewDetail(olt)}>
                                <Eye className="size-4" />
                              </Button>
                              <Button variant="ghost" size="icon" className="size-8" onClick={() => handleOpenEdit(olt)}>
                                <Pencil className="size-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="icon"
                                className="size-8 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
                                onClick={() => setDeleteTarget(olt)}
                              >
                                <Trash2 className="size-4" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
              <div className="px-4 pb-4">
                <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Add/Edit OLT Dialog */}
      <Dialog open={formOpen} onOpenChange={setFormOpen}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {editingOLT ? <Pencil className="size-5" /> : <Plus className="size-5" />}
              {editingOLT ? 'Edit OLT Device' : 'Add OLT Device'}
            </DialogTitle>
            <DialogDescription>
              {editingOLT ? 'Update OLT device details' : 'Register a new OLT device to your network'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Device Name *</Label>
                <Input
                  className="mt-1.5"
                  placeholder="e.g., OLT-Office-01"
                  value={form.name}
                  onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
                />
              </div>
              <div>
                <Label>IP Address *</Label>
                <Input
                  className="mt-1.5"
                  placeholder="e.g., 192.168.1.1"
                  value={form.ipAddress}
                  onChange={(e) => setForm((prev) => ({ ...prev, ipAddress: e.target.value }))}
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Username</Label>
                <Input
                  className="mt-1.5"
                  placeholder="SNMP/SSH username"
                  value={form.username}
                  onChange={(e) => setForm((prev) => ({ ...prev, username: e.target.value }))}
                />
              </div>
              <div>
                <Label>Password{editingOLT ? ' (leave blank to keep)' : ''}</Label>
                <Input
                  type="password"
                  className="mt-1.5"
                  placeholder="••••••••"
                  value={form.password}
                  onChange={(e) => setForm((prev) => ({ ...prev, password: e.target.value }))}
                />
              </div>
            </div>
            <div className="grid grid-cols-3 gap-3">
              <div>
                <Label>Model</Label>
                <Input
                  className="mt-1.5"
                  placeholder="e.g., ZTE C320"
                  value={form.model}
                  onChange={(e) => setForm((prev) => ({ ...prev, model: e.target.value }))}
                />
              </div>
              <div>
                <Label>Firmware</Label>
                <Input
                  className="mt-1.5"
                  placeholder="e.g., V2.1.0"
                  value={form.firmware}
                  onChange={(e) => setForm((prev) => ({ ...prev, firmware: e.target.value }))}
                />
              </div>
              <div>
                <Label>Port Count</Label>
                <Input
                  type="number"
                  className="mt-1.5"
                  placeholder="16"
                  value={form.portCount}
                  onChange={(e) => setForm((prev) => ({ ...prev, portCount: e.target.value }))}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFormOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSubmit} disabled={submitting}>
              {submitting ? (
                <Loader2 className="size-4 animate-spin" />
              ) : editingOLT ? (
                <Pencil className="size-4" />
              ) : (
                <Plus className="size-4" />
              )}
              {editingOLT ? 'Update OLT' : 'Create OLT'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={!!deleteTarget} onOpenChange={() => setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete OLT Device</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete &quot;{deleteTarget?.name}&quot;? This action cannot be
              undone. OLT devices with connected ONUs cannot be deleted.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={deleting}
              className="bg-red-600 hover:bg-red-700"
            >
              {deleting ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* OLT 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">
                    <Server className="size-6 text-slate-600 dark:text-slate-400" />
                  </div>
                  <div className="min-w-0">
                    <DialogTitle className="text-lg">{detailData?.name}</DialogTitle>
                    <DialogDescription className="flex items-center gap-2 mt-1">
                      <Badge variant="secondary" className={oltStatusColor[detailData?.status || '']}>
                        {detailData?.status || 'N/A'}
                      </Badge>
                      <span className="font-mono text-xs">{detailData?.ipAddress}</span>
                    </DialogDescription>
                  </div>
                </div>
              </DialogHeader>

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

                  {/* Device Info */}
                  <div>
                    <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <Monitor className="size-4" />
                      Device Information
                    </h4>
                    <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Name</p>
                        <p className="text-sm font-medium mt-0.5">{detailData.name}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">IP Address</p>
                        <p className="text-sm font-mono font-medium mt-0.5">{detailData.ipAddress}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Model</p>
                        <p className="text-sm font-medium mt-0.5">{detailData.model || '—'}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Firmware</p>
                        <p className="text-sm font-medium mt-0.5">{detailData.firmware || '—'}</p>
                      </div>
                      <div className="rounded-lg bg-muted/50 p-3">
                        <p className="text-xs text-muted-foreground">Port Count</p>
                        <p className="text-sm font-medium mt-0.5 flex items-center gap-1">
                          <EthernetPort className="size-3.5" />
                          {detailData.portCount}
                        </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 />

                  {/* Status Breakdown */}
                  <div>
                    <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <Activity className="size-4" />
                      ONU Status Breakdown
                    </h4>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                      <div className="rounded-lg border p-3 text-center">
                        <p className="text-2xl font-bold">{detailData._count.onus}</p>
                        <p className="text-xs text-muted-foreground">Total ONUs</p>
                      </div>
                      <div className="rounded-lg border p-3 text-center">
                        <p className="text-2xl font-bold text-emerald-600">{detailData._count.onusOnline}</p>
                        <p className="text-xs text-muted-foreground">Online</p>
                      </div>
                      <div className="rounded-lg border p-3 text-center">
                        <p className="text-2xl font-bold text-gray-500">{detailData.onuStatusCounts.offline}</p>
                        <p className="text-xs text-muted-foreground">Offline</p>
                      </div>
                      <div className="rounded-lg border p-3 text-center">
                        <p className="text-2xl font-bold text-red-600">{detailData.onuStatusCounts.faulty}</p>
                        <p className="text-xs text-muted-foreground">Faulty</p>
                      </div>
                    </div>
                  </div>

                  <Separator />

                  {/* Connected ONUs List */}
                  <div>
                    <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                      <Cpu className="size-4" />
                      Connected ONUs ({detailData.onus.length})
                    </h4>
                    {detailData.onus.length > 0 ? (
                      <div className="space-y-2 max-h-72 overflow-y-auto">
                        {detailData.onus.map((onu) => (
                          <div
                            key={onu.id}
                            className="flex items-center justify-between py-2 px-3 rounded-lg border gap-3"
                          >
                            <div className="flex items-center gap-3 min-w-0">
                              <Badge variant="outline" className="font-mono text-xs shrink-0">
                                {onu.slot}/{onu.port}
                              </Badge>
                              <div className="min-w-0">
                                <p className="text-sm font-mono font-medium truncate">{onu.serialNumber}</p>
                                <p className="text-xs text-muted-foreground truncate">
                                  {onu.user ? onu.user.name : 'Unassigned'}
                                </p>
                              </div>
                            </div>
                            <div className="flex items-center gap-2 shrink-0">
                              <span className="text-xs text-muted-foreground hidden sm:inline">
                                {onu.signalStrength} dBm
                              </span>
                              <Badge variant="secondary" className={onuStatusColor[onu.status] || ''}>
                                {onu.status}
                              </Badge>
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground py-4 text-center">No connected ONUs</p>
                    )}
                  </div>
                </>
              ) : (
                <p className="text-sm text-muted-foreground text-center py-8">Failed to load OLT details</p>
              )}
            </div>
          </ScrollArea>
        </DialogContent>
      </Dialog>
    </div>
  )
}
