'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import {
  Search,
  Filter,
  Download,
  MoreHorizontal,
  Eye,
  Pencil,
  Ban,
  CheckCircle,
  Trash2,
  Send,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  Users,
  UserX,
  Wifi,
  WifiOff,
  Clock,
  AlertTriangle,
  UserPlus,
  TrendingUp,
  DollarSign,
  Loader2,
  X,
  Mail,
  Phone,
  MapPin,
  Globe,
  Router,
  Calendar,
  FileText,
  CreditCard,
  Activity,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { api } from '@/lib/api'
import { useAppStore, type ClientTabType } from '@/store/app-store'

// ---- Types ----
interface ClientUser {
  id: string
  email: string
  name: string
  phone: string
  username: string
  role: string
  status: string
  address: string
  areaId: string | null
  connectionType: string
  ipAddress: string
  macAddress: string
  avatar: string
  createdAt: string
  updatedAt: string
  area: { id: string; name: string; code: string } | null
  reseller: { id: string; name: string; email: string } | null
  _count: {
    subscriptions: { where: { status: string } }[]
    invoices: number
    tickets: { where: { status: string | string[] } }[]
  }
}

interface Plan {
  id: string
  name: string
  price: number
  speedDown: number
  speedUp: number
  duration: number
}

interface Area {
  id: string
  name: string
  code: string
}

interface Invoice {
  id: string
  invoiceNumber: string
  totalAmount: number
  paidAmount: number
  status: string
  dueDate: string
  createdAt: string
}

interface ClientDetailData {
  user: ClientUser
  subscriptions: Array<{
    id: string
    startDate: string
    expiryDate: string
    status: string
    autoRenew: boolean
    plan: Plan
  }>
  invoices: Invoice[]
  payments: Array<{
    id: string
    amount: number
    method: string
    status: string
    createdAt: string
  }>
  sessions: Array<{
    id: string
    startTime: string
    stopTime: string | null
    duration: number
    downloadBytes: number
    uploadBytes: number
    isActive: boolean
  }>
}

// ---- Helpers ----
function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('en-BD', {
    style: 'currency',
    currency: 'BDT',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(amount)
}

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

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

function formatDuration(seconds: number): string {
  if (seconds === 0) return '0s'
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  if (h > 0) return `${h}h ${m}m`
  if (m > 0) return `${m}m ${s}s`
  return `${s}s`
}

const statusColor: Record<string, string> = {
  ACTIVE: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  EXPIRED: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
  SUSPENDED: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
  CLOSED: 'bg-gray-100 text-gray-600 dark:bg-gray-800/30 dark:text-gray-400',
  PENDING: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
}

const connectionTypeColor: Record<string, string> = {
  FIBER: 'bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-400',
  WIRELESS: 'bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-400',
  DIALUP: 'bg-gray-100 text-gray-600 dark:bg-gray-800/30 dark:text-gray-400',
  ETHERNET: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
}

const invoiceStatusColor: Record<string, string> = {
  PAID: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  UNPAID: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  DUE: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
  PARTIAL: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
}

// Tab definitions
const CLIENT_TABS: { value: ClientTabType; label: string; icon: React.ElementType }[] = [
  { value: 'active', label: 'Active', icon: CheckCircle },
  { value: 'expired', label: 'Expired', icon: AlertTriangle },
  { value: 'suspended', label: 'Suspended', icon: Ban },
  { value: 'closed', label: 'Closed', icon: UserX },
  { value: 'pending', label: 'Pending', icon: Clock },
  { value: 'online', label: 'Online', icon: Wifi },
  { value: 'offline', label: 'Offline', icon: WifiOff },
  { value: 'new', label: 'New', icon: UserPlus },
  { value: 'high-usage', label: 'High Usage', icon: TrendingUp },
  { value: 'due-payment', label: 'Due Payment', icon: DollarSign },
]

// Get API params from tab
function getTabParams(tab: ClientTabType): Record<string, string> {
  switch (tab) {
    case 'active':
      return { status: 'ACTIVE' }
    case 'expired':
      return { status: 'EXPIRED' }
    case 'suspended':
      return { status: 'SUSPENDED' }
    case 'closed':
      return { status: 'CLOSED' }
    case 'pending':
      return { status: 'PENDING' }
    case 'online':
      return { status: 'ACTIVE' } // Simulated
    case 'offline':
      return { status: 'EXPIRED' } // Simulated
    case 'new':
      return { sortBy: 'createdAt', sortOrder: 'desc' }
    case 'high-usage':
      return { status: 'ACTIVE' } // Simulated
    case 'due-payment':
      return {} // Special handling
    default:
      return {}
  }
}

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

// ---- Client Detail Dialog ----
function ClientDetailDialog({
  client,
  open,
  onOpenChange,
}: {
  client: ClientDetailData | null
  open: boolean
  onOpenChange: (open: boolean) => void
}) {
  if (!client) return null

  const { user } = client
  const activeSubscription = client.subscriptions.find((s) => s.status === 'ACTIVE')
  const latestSubscription = client.subscriptions[0]

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <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-full bg-primary/10 text-primary shrink-0">
                  <span className="text-lg font-bold">
                    {user.name.charAt(0).toUpperCase()}
                  </span>
                </div>
                <div className="min-w-0">
                  <DialogTitle className="text-lg">{user.name}</DialogTitle>
                  <DialogDescription className="flex items-center gap-2 mt-1">
                    <Badge variant="secondary" className={statusColor[user.status] || ''}>
                      {user.status}
                    </Badge>
                    <Badge variant="secondary" className={connectionTypeColor[user.connectionType] || ''}>
                      {user.connectionType}
                    </Badge>
                    <span className="text-xs text-muted-foreground">ID: {user.id.slice(0, 8)}</span>
                  </DialogDescription>
                </div>
              </div>
            </DialogHeader>

            <Separator />

            {/* Client Info */}
            <div>
              <h4 className="text-sm font-semibold mb-3">Client Information</h4>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <InfoItem icon={Mail} label="Email" value={user.email} />
                <InfoItem icon={Phone} label="Phone" value={user.phone || 'N/A'} />
                <InfoItem icon={UserPlus} label="Username" value={user.username || 'N/A'} />
                <InfoItem icon={MapPin} label="Area" value={user.area?.name || 'Unassigned'} />
                <InfoItem icon={Globe} label="IP Address" value={user.ipAddress || 'N/A'} />
                <InfoItem icon={Router} label="MAC Address" value={user.macAddress || 'N/A'} />
                <InfoItem
                  icon={MapPin}
                  label="Address"
                  value={user.address || 'N/A'}
                  className="sm:col-span-2"
                />
              </div>
            </div>

            <Separator />

            {/* Subscription Info */}
            <div>
              <h4 className="text-sm font-semibold mb-3">Subscription</h4>
              {activeSubscription ? (
                <Card className="p-4">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <p className="text-xs text-muted-foreground">Plan</p>
                      <p className="text-sm font-semibold">{activeSubscription.plan.name}</p>
                      <p className="text-xs text-muted-foreground">
                        {activeSubscription.plan.speedDown}/{activeSubscription.plan.speedUp} Mbps &middot;{' '}
                        {formatCurrency(activeSubscription.plan.price)}/mo
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">Status</p>
                      <Badge variant="secondary" className={statusColor[activeSubscription.status] || ''}>
                        {activeSubscription.status}
                      </Badge>
                      {activeSubscription.autoRenew && (
                        <p className="text-xs text-muted-foreground mt-1">Auto-renew enabled</p>
                      )}
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">Start Date</p>
                      <p className="text-sm">{formatDate(activeSubscription.startDate)}</p>
                    </div>
                    <div>
                      <p className="text-xs text-muted-foreground">Expiry Date</p>
                      <p className="text-sm">{formatDate(activeSubscription.expiryDate)}</p>
                    </div>
                  </div>
                </Card>
              ) : latestSubscription ? (
                <Card className="p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <Badge variant="secondary" className={statusColor[latestSubscription.status] || ''}>
                      {latestSubscription.status}
                    </Badge>
                    <span className="text-sm font-medium">{latestSubscription.plan.name}</span>
                  </div>
                  <p className="text-xs text-muted-foreground">
                    Expired: {formatDate(latestSubscription.expiryDate)}
                  </p>
                </Card>
              ) : (
                <p className="text-sm text-muted-foreground">No subscriptions found</p>
              )}
            </div>

            <Separator />

            {/* Invoice History */}
            <div>
              <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                <FileText className="size-4" />
                Recent Invoices
              </h4>
              {client.invoices.length > 0 ? (
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  {client.invoices.map((inv) => (
                    <div key={inv.id} className="flex items-center justify-between py-2 border-b last:border-0">
                      <div className="flex items-center gap-3">
                        <span className="font-mono text-xs text-muted-foreground">{inv.invoiceNumber}</span>
                        <Badge variant="secondary" className={invoiceStatusColor[inv.status] || ''}>
                          {inv.status}
                        </Badge>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium">{formatCurrency(inv.totalAmount)}</p>
                        <p className="text-xs text-muted-foreground">{formatDate(inv.createdAt)}</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">No invoices</p>
              )}
            </div>

            <Separator />

            {/* Payment History */}
            <div>
              <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                <CreditCard className="size-4" />
                Recent Payments
              </h4>
              {client.payments.length > 0 ? (
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  {client.payments.map((pay) => (
                    <div key={pay.id} className="flex items-center justify-between py-2 border-b last:border-0">
                      <div className="flex items-center gap-3">
                        <Badge variant="outline">{pay.method}</Badge>
                        <Badge variant="secondary" className={invoiceStatusColor[pay.status] || ''}>
                          {pay.status}
                        </Badge>
                      </div>
                      <div className="text-right">
                        <p className="text-sm font-medium">{formatCurrency(pay.amount)}</p>
                        <p className="text-xs text-muted-foreground">{formatDate(pay.createdAt)}</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">No payments</p>
              )}
            </div>

            <Separator />

            {/* Session History */}
            <div>
              <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                <Activity className="size-4" />
                Recent Sessions
              </h4>
              {client.sessions.length > 0 ? (
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  {client.sessions.map((session) => (
                    <div key={session.id} className="flex items-center justify-between py-2 border-b last:border-0">
                      <div className="flex items-center gap-3">
                        <Badge variant={session.isActive ? 'default' : 'secondary'}>
                          {session.isActive ? 'Online' : 'Offline'}
                        </Badge>
                        <span className="text-xs text-muted-foreground">
                          {formatDate(session.startTime)}
                        </span>
                      </div>
                      <div className="text-right">
                        <p className="text-xs text-muted-foreground">
                          {formatDuration(session.duration)}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {formatBytes(session.downloadBytes)} / {formatBytes(session.uploadBytes)}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">No sessions</p>
              )}
            </div>
          </div>
        </ScrollArea>
      </DialogContent>
    </Dialog>
  )
}

function InfoItem({
  icon: Icon,
  label,
  value,
  className = '',
}: {
  icon: React.ElementType
  label: string
  value: string
  className?: string
}) {
  return (
    <div className={`flex items-center gap-2 ${className}`}>
      <Icon className="size-4 text-muted-foreground shrink-0" />
      <div className="min-w-0">
        <p className="text-xs text-muted-foreground">{label}</p>
        <p className="text-sm truncate">{value}</p>
      </div>
    </div>
  )
}

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

// ---- Main Component ----
export default function ClientsView() {
  const {
    clientTab,
    setClientTab,
    selectedClientIds,
    toggleClientSelection,
    selectAllClients,
    clearClientSelection,
  } = useAppStore()

  // Data state
  const [clients, setClients] = useState<ClientUser[]>([])
  const [total, setTotal] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Filter state
  const [searchQuery, setSearchQuery] = useState('')
  const [searchInput, setSearchInput] = useState('')
  const [areaFilter, setAreaFilter] = useState<string>('')
  const [planFilter, setPlanFilter] = useState<string>('')
  const [connectionTypeFilter, setConnectionTypeFilter] = useState<string>('')
  const [page, setPage] = useState(1)
  const [perPage, setPerPage] = useState(25)

  // Reference data
  const [areas, setAreas] = useState<Area[]>([])
  const [plans, setPlans] = useState<Plan[]>([])

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

  // Sort
  const [sortBy, setSortBy] = useState<string>('createdAt')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')

  // Fetch reference data (areas, plans)
  useEffect(() => {
    async function fetchReferences() {
      const [areasRes, plansRes] = await Promise.all([
        api.get<{ data: { areas: Area[] } }>('/api/areas', { limit: 100 }),
        api.get<{ data: { plans: Plan[] } }>('/api/plans', { limit: 100 }),
      ])
      if (areasRes.success && areasRes.data) setAreas(areasRes.data.data.areas)
      if (plansRes.success && plansRes.data) setPlans(plansRes.data.data.plans)
    }
    fetchReferences()
  }, [])

  // Fetch clients
  const fetchClients = useCallback(async () => {
    setLoading(true)
    setError(null)
    clearClientSelection()

    try {
      const tabParams = getTabParams(clientTab)

      // Special handling for due-payment tab
      if (clientTab === 'due-payment') {
        const dueRes = await api.get<{
          data: { invoices: Invoice[]; pagination: { total: number; totalPages: number } }
        }>('/api/invoices', {
          status: 'UNPAID',
          limit: perPage,
          page,
        })

        if (!dueRes.success || !dueRes.data) {
          setError(dueRes.error || 'Failed to load clients')
          setLoading(false)
          return
        }

        const invoices = dueRes.data.data.invoices
        // Extract unique user IDs
        const uniqueUserIds = [...new Set(invoices.map((inv) => (inv as unknown as { userId: string }).userId))]
        // Fetch those users
        if (uniqueUserIds.length > 0) {
          const usersRes = await api.get<{ data: { users: ClientUser[] } }>('/api/users', {
            limit: perPage,
            page: 1,
          })
          if (usersRes.success && usersRes.data) {
            // Filter users that have due invoices
            const dueUserIds = new Set(
              invoices.map((inv) => (inv as unknown as { userId: string }).userId)
            )
            const filteredUsers = usersRes.data.data.users.filter((u) => dueUserIds.has(u.id))
            setClients(filteredUsers)
            setTotal(dueRes.data.data.pagination.total)
            setTotalPages(dueRes.data.data.pagination.totalPages)
          }
        } else {
          setClients([])
          setTotal(0)
          setTotalPages(0)
        }
        setLoading(false)
        return
      }

      const params: Record<string, string | number> = {
        ...tabParams,
        limit: perPage,
        page,
        sortBy,
        sortOrder,
      }

      if (searchQuery) params.search = searchQuery
      if (areaFilter) params.areaId = areaFilter
      if (connectionTypeFilter) params.connectionType = connectionTypeFilter

      const res = await api.get<{ data: { users: ClientUser[]; pagination: { page: number; limit: number; total: number; totalPages: number } } }>(
        '/api/users',
        params
      )

      if (res.success && res.data) {
        setClients(res.data.data.users)
        setTotal(res.data.data.pagination.total)
        setTotalPages(res.data.data.pagination.totalPages)
      } else {
        setError(res.error || 'Failed to load clients')
      }
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Network error'
      setError(message)
    } finally {
      setLoading(false)
    }
  }, [clientTab, searchQuery, areaFilter, connectionTypeFilter, page, perPage, sortBy, sortOrder, clearClientSelection])

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

  // Reset page when tab/filters change
  useEffect(() => {
    setPage(1)
  }, [clientTab, searchQuery, areaFilter, connectionTypeFilter, perPage])

  // Search handler with debounce
  useEffect(() => {
    const timeout = setTimeout(() => {
      setSearchQuery(searchInput)
    }, 400)
    return () => clearTimeout(timeout)
  }, [searchInput])

  // Handle view client detail
  const handleViewClient = async (client: ClientUser) => {
    setDetailOpen(true)
    setDetailLoading(true)
    try {
      const [userRes, subsRes, invRes, payRes, sessRes] = await Promise.all([
        api.get<{ data: ClientUser }>(`/api/users/${client.id}`),
        api.get<{ data: Array<{ id: string; startDate: string; expiryDate: string; status: string; autoRenew: boolean; plan: Plan }> }>(
          '/api/subscriptions',
          { userId: client.id, limit: 10 }
        ),
        api.get<{ data: { invoices: Invoice[] } }>('/api/invoices', { userId: client.id, limit: 5 }),
        api.get<{ data: Array<{ id: string; amount: number; method: string; status: string; createdAt: string }> }>(
          '/api/payments',
          { userId: client.id, limit: 5 }
        ),
        api.get<{ data: Array<{ id: string; startTime: string; stopTime: string | null; duration: number; downloadBytes: number; uploadBytes: number; isActive: boolean }> }>(
          '/api/logs',
          { userId: client.id, limit: 5 }
        ),
      ])

      const userData = userRes.success ? userRes.data?.data : client
      const subsData = subsRes.success ? subsRes.data?.data || [] : []
      const invData = invRes.success ? invRes.data?.data?.invoices || [] : []
      const payData = payRes.success ? payRes.data?.data || [] : []
      const sessData = sessRes.success ? sessRes.data?.data || [] : []

      setDetailData({
        user: userData || client,
        subscriptions: subsData,
        invoices: invData,
        payments: payData,
        sessions: sessData,
      })
    } catch {
      setDetailData({
        user: client,
        subscriptions: [],
        invoices: [],
        payments: [],
        sessions: [],
      })
    } finally {
      setDetailLoading(false)
    }
  }

  // Bulk action handler
  const handleBulkAction = async (action: string) => {
    if (selectedClientIds.length === 0) return

    try {
      const res = await api.post('/api/users/bulk', {
        userIds: selectedClientIds,
        action,
      })

      if (res.success) {
        clearClientSelection()
        fetchClients()
      }
    } catch {
      // Error handling
    }
  }

  // Export CSV handler
  const handleExportCSV = () => {
    const headers = ['Name', 'Email', 'Phone', 'Status', 'Area', 'Connection Type', 'IP Address', 'Created']
    const rows = clients.map((c) => [
      c.name,
      c.email,
      c.phone,
      c.status,
      c.area?.name || '',
      c.connectionType,
      c.ipAddress,
      new Date(c.createdAt).toLocaleDateString(),
    ])

    const csv = [headers.join(','), ...rows.map((r) => r.map((v) => `"${v}"`).join(','))].join('\n')
    const blob = new Blob([csv], { type: 'text/csv' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `clients-${clientTab}-${new Date().toISOString().split('T')[0]}.csv`
    a.click()
    URL.revokeObjectURL(url)
  }

  // Toggle sort
  const handleSort = (column: string) => {
    if (sortBy === column) {
      setSortOrder((prev) => (prev === 'asc' ? 'desc' : 'asc'))
    } else {
      setSortBy(column)
      setSortOrder('asc')
    }
  }

  // Select all on current page
  const allSelected = clients.length > 0 && clients.every((c) => selectedClientIds.includes(c.id))

  const handleSelectAll = () => {
    if (allSelected) {
      clearClientSelection()
    } else {
      selectAllClients(clients.map((c) => c.id))
    }
  }

  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">Client Management</h1>
          <p className="text-muted-foreground mt-1">
            Manage your ISP clients, subscriptions, and connections
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleExportCSV}>
            <Download className="size-4" />
            Export CSV
          </Button>
          <Button size="sm">
            <UserPlus className="size-4" />
            Add Client
          </Button>
        </div>
      </div>

      {/* Search & Filter Bar */}
      <Card className="p-4">
        <div className="flex flex-col lg:flex-row gap-3">
          {/* Search */}
          <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, phone, IP, or username..."
              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>

          {/* Filters */}
          <div className="flex flex-wrap gap-2">
            <Select value={areaFilter} onValueChange={(v) => setAreaFilter(v === 'all' ? '' : v)}>
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="Area" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Areas</SelectItem>
                {areas.map((area) => (
                  <SelectItem key={area.id} value={area.id}>
                    {area.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={planFilter} onValueChange={(v) => setPlanFilter(v === 'all' ? '' : v)}>
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="Plan" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Plans</SelectItem>
                {plans.map((plan) => (
                  <SelectItem key={plan.id} value={plan.id}>
                    {plan.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select
              value={connectionTypeFilter}
              onValueChange={(v) => setConnectionTypeFilter(v === 'all' ? '' : v)}
            >
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="Connection" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Types</SelectItem>
                <SelectItem value="FIBER">Fiber</SelectItem>
                <SelectItem value="WIRELESS">Wireless</SelectItem>
                <SelectItem value="DIALUP">Dial-up</SelectItem>
                <SelectItem value="ETHERNET">Ethernet</SelectItem>
              </SelectContent>
            </Select>

            {/* Per page */}
            <Select
              value={String(perPage)}
              onValueChange={(v) => setPerPage(Number(v))}
            >
              <SelectTrigger className="w-[90px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="10">10</SelectItem>
                <SelectItem value="25">25</SelectItem>
                <SelectItem value="50">50</SelectItem>
              </SelectContent>
            </Select>

            {/* Bulk Actions */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={selectedClientIds.length === 0}
                  className="gap-2"
                >
                  <Filter className="size-4" />
                  Bulk Actions
                  {selectedClientIds.length > 0 && (
                    <Badge variant="secondary" className="ml-1">
                      {selectedClientIds.length}
                    </Badge>
                  )}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel>Actions for {selectedClientIds.length} selected</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => handleBulkAction('activate')}>
                  <CheckCircle className="size-4 mr-2 text-emerald-500" />
                  Activate
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleBulkAction('suspend')}>
                  <Ban className="size-4 mr-2 text-orange-500" />
                  Suspend
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => handleBulkAction('notify')}>
                  <Send className="size-4 mr-2 text-blue-500" />
                  Send Notification
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onClick={() => handleBulkAction('delete')}
                  variant="destructive"
                >
                  <Trash2 className="size-4 mr-2" />
                  Delete
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </Card>

      {/* Tabs */}
      <Tabs value={clientTab} onValueChange={(v) => setClientTab(v as ClientTabType)}>
        <ScrollArea className="w-full -mx-4 px-4">
          <TabsList className="w-full flex-wrap h-auto gap-1 bg-transparent p-0 justify-start">
            {CLIENT_TABS.map((tab) => (
              <TabsTrigger
                key={tab.value}
                value={tab.value}
                className="data-[state=active]:bg-primary data-[state=active]:text-primary-foreground border rounded-lg px-3 py-1.5 gap-1.5 text-sm"
              >
                <tab.icon className="size-3.5" />
                <span className="hidden sm:inline">{tab.label}</span>
              </TabsTrigger>
            ))}
          </TabsList>
        </ScrollArea>

        {/* Single content for all tabs - we handle tab logic via fetch */}
        <TabsContent value={clientTab} className="mt-4">
          <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={fetchClients} variant="outline">
                    Retry
                  </Button>
                </div>
              ) : loading ? (
                <div className="p-4">
                  <TableSkeleton />
                </div>
              ) : (
                <div>
                  {/* Results count */}
                  <div className="flex items-center justify-between px-4 py-3 border-b">
                    <p className="text-sm text-muted-foreground">
                      Showing {clients.length} of {total} clients
                    </p>
                    {selectedClientIds.length > 0 && (
                      <div className="flex items-center gap-2">
                        <span className="text-sm text-muted-foreground">
                          {selectedClientIds.length} selected
                        </span>
                        <Button variant="ghost" size="sm" onClick={clearClientSelection}>
                          Clear
                        </Button>
                      </div>
                    )}
                  </div>

                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-10">
                          <Checkbox
                            checked={allSelected}
                            onCheckedChange={handleSelectAll}
                          />
                        </TableHead>
                        <TableHead
                          className="cursor-pointer select-none"
                          onClick={() => handleSort('name')}
                        >
                          <span className="flex items-center gap-1">
                            Name
                            {sortBy === 'name' && (
                              <span className="text-xs text-muted-foreground">
                                {sortOrder === 'asc' ? '↑' : '↓'}
                              </span>
                            )}
                          </span>
                        </TableHead>
                        <TableHead className="hidden md:table-cell">Email</TableHead>
                        <TableHead className="hidden lg:table-cell">Phone</TableHead>
                        <TableHead className="hidden md:table-cell">Area</TableHead>
                        <TableHead className="hidden lg:table-cell">Plan</TableHead>
                        <TableHead>Connection</TableHead>
                        <TableHead>Status</TableHead>
                        <TableHead
                          className="hidden md:table-cell cursor-pointer select-none"
                          onClick={() => handleSort('createdAt')}
                        >
                          <span className="flex items-center gap-1">
                            Created
                            {sortBy === 'createdAt' && (
                              <span className="text-xs text-muted-foreground">
                                {sortOrder === 'asc' ? '↑' : '↓'}
                              </span>
                            )}
                          </span>
                        </TableHead>
                        <TableHead className="w-16">Actions</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {clients.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={10} className="h-32 text-center">
                            <div className="flex flex-col items-center gap-2">
                              <Users className="size-8 text-muted-foreground opacity-50" />
                              <p className="text-muted-foreground text-sm">No clients found</p>
                            </div>
                          </TableCell>
                        </TableRow>
                      ) : (
                        clients.map((client) => (
                          <TableRow
                            key={client.id}
                            className="cursor-pointer"
                            data-state={selectedClientIds.includes(client.id) ? 'selected' : undefined}
                          >
                            <TableCell onClick={(e) => e.stopPropagation()}>
                              <Checkbox
                                checked={selectedClientIds.includes(client.id)}
                                onCheckedChange={() => toggleClientSelection(client.id)}
                              />
                            </TableCell>
                            <TableCell onClick={() => handleViewClient(client)}>
                              <div className="flex items-center gap-2">
                                <div className="flex items-center justify-center size-8 rounded-full bg-primary/10 text-primary shrink-0 text-xs font-bold">
                                  {client.name.charAt(0).toUpperCase()}
                                </div>
                                <div className="min-w-0">
                                  <p className="font-medium text-sm truncate max-w-[150px]">
                                    {client.name}
                                  </p>
                                  <p className="text-xs text-muted-foreground md:hidden truncate max-w-[150px]">
                                    {client.email}
                                  </p>
                                </div>
                              </div>
                            </TableCell>
                            <TableCell
                              className="hidden md:table-cell text-muted-foreground text-sm"
                              onClick={() => handleViewClient(client)}
                            >
                              <span className="truncate max-w-[180px] block">{client.email}</span>
                            </TableCell>
                            <TableCell
                              className="hidden lg:table-cell text-muted-foreground text-sm"
                              onClick={() => handleViewClient(client)}
                            >
                              {client.phone || '—'}
                            </TableCell>
                            <TableCell
                              className="hidden md:table-cell"
                              onClick={() => handleViewClient(client)}
                            >
                              <Badge variant="outline" className="font-normal">
                                {client.area?.name || 'N/A'}
                              </Badge>
                            </TableCell>
                            <TableCell
                              className="hidden lg:table-cell text-sm"
                              onClick={() => handleViewClient(client)}
                            >
                              {client._count.subscriptions[0] ? (
                                <Badge variant="outline" className="font-normal">
                                  Active Plan
                                </Badge>
                              ) : (
                                <span className="text-muted-foreground">—</span>
                              )}
                            </TableCell>
                            <TableCell onClick={() => handleViewClient(client)}>
                              <Badge
                                variant="secondary"
                                className={connectionTypeColor[client.connectionType] || ''}
                              >
                                {client.connectionType}
                              </Badge>
                            </TableCell>
                            <TableCell onClick={() => handleViewClient(client)}>
                              <Badge
                                variant="secondary"
                                className={statusColor[client.status] || ''}
                              >
                                {client.status}
                              </Badge>
                            </TableCell>
                            <TableCell
                              className="hidden md:table-cell text-muted-foreground text-xs"
                              onClick={() => handleViewClient(client)}
                            >
                              {formatDate(client.createdAt)}
                            </TableCell>
                            <TableCell onClick={(e) => e.stopPropagation()}>
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button variant="ghost" size="icon" className="size-8">
                                    <MoreHorizontal className="size-4" />
                                    <span className="sr-only">Actions</span>
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuItem onClick={() => handleViewClient(client)}>
                                    <Eye className="size-4 mr-2" />
                                    View Details
                                  </DropdownMenuItem>
                                  <DropdownMenuItem>
                                    <Pencil className="size-4 mr-2" />
                                    Edit
                                  </DropdownMenuItem>
                                  <DropdownMenuSeparator />
                                  {client.status === 'ACTIVE' ? (
                                    <DropdownMenuItem>
                                      <Ban className="size-4 mr-2 text-orange-500" />
                                      Suspend
                                    </DropdownMenuItem>
                                  ) : client.status === 'SUSPENDED' ? (
                                    <DropdownMenuItem>
                                      <CheckCircle className="size-4 mr-2 text-emerald-500" />
                                      Activate
                                    </DropdownMenuItem>
                                  ) : null}
                                  <DropdownMenuItem>
                                    <Send className="size-4 mr-2 text-blue-500" />
                                    Send Notification
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>

                  {/* Pagination */}
                  <div className="px-4 pb-4">
                    <Pagination
                      page={page}
                      totalPages={totalPages}
                      onPageChange={setPage}
                    />
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Client Detail Dialog */}
      <ClientDetailDialog
        client={detailData}
        open={detailOpen}
        onOpenChange={setDetailOpen}
      />

      {/* Detail loading overlay */}
      {detailLoading && detailOpen && (
        <div className="fixed inset-0 z-50 bg-background/50 flex items-center justify-center">
          <Loader2 className="size-8 animate-spin text-primary" />
        </div>
      )}
    </div>
  )
}
