'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Search,
  Eye,
  RefreshCcw,
  Loader2,
  ChevronLeft,
  ChevronRight,
  Users,
  Wallet,
  Clock,
  TrendingUp,
  Edit3,
  XCircle,
  DollarSign,
  Phone,
  Mail,
  Calendar,
  ArrowUpRight,
  ArrowDownLeft,
  SlidersHorizontal,
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'

// ── Types ──────────────────────────────────────────────────────────────────────

interface ResellerUser {
  id: string
  name: string
  email: string
  phone: string
  status: string
}

interface Reseller {
  id: string
  userId: string
  commissionType: string
  commissionValue: number
  walletBalance: number
  totalEarned: number
  isActive: boolean
  createdAt: string
  updatedAt: string
  user: ResellerUser
  totalCommission: number
  totalTransactions: number
  pendingCommission: number
  paidCommission: number
  _count?: {
    clients: number
    commissions: number
  }
}

interface Commission {
  id: string
  resellerId: string
  userId: string
  invoiceId: string
  amount: number
  type: string
  status: string
  createdAt: string
  invoice?: { id: string; invoiceNumber: string; totalAmount: number }
  user?: { id: string; name: string; email: string }
}

interface ResellerTransaction {
  id: string
  resellerId: string
  amount: number
  type: string
  description: string
  createdAt: string
}

interface ResellerDetail extends Omit<Reseller, '_count'> {
  commissions: Commission[]
  transactions: ResellerTransaction[]
  commissionBreakdown: { status: string; _sum: { amount: number | null }; _count: number }[]
  _count: { clients: number; commissions: number }
}

interface ResellerSummary {
  totalResellers: number
  totalCommissionPaid: number
  pendingPayouts: number
  thisMonthEarnings: number
}

// ── Constants ──────────────────────────────────────────────────────────────────

const statusBadgeColors: Record<string, string> = {
  PENDING: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-400',
  PAID: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400',
  CANCELLED: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-400',
}

const transactionTypeBadge: Record<string, string> = {
  COMMISSION: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400',
  WITHDRAWAL: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-400',
  ADJUSTMENT: 'bg-sky-100 text-sky-800 dark:bg-sky-900/40 dark:text-sky-400',
}

// ── 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', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}

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

// ── Component ──────────────────────────────────────────────────────────────────

export default function ResellersView() {
  const { toast } = useToast()

  // List state
  const [resellers, setResellers] = useState<Reseller[]>([])
  const [summary, setSummary] = useState<ResellerSummary | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)

  // Filters
  const [searchQuery, setSearchQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')

  // Detail dialog
  const [detailOpen, setDetailOpen] = useState(false)
  const [selectedReseller, setSelectedReseller] = useState<ResellerDetail | null>(null)
  const [detailLoading, setDetailLoading] = useState(false)

  // Edit commission dialog
  const [editOpen, setEditOpen] = useState(false)
  const [editReseller, setEditReseller] = useState<Reseller | null>(null)
  const [editCommissionType, setEditCommissionType] = useState('PERCENTAGE')
  const [editCommissionValue, setEditCommissionValue] = useState('')
  const [saving, setSaving] = useState(false)

  const fetchResellers = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)
      const res = await api.get<{
        success: boolean
        data: {
          resellers: Reseller[]
          pagination: { page: number; limit: number; total: number; totalPages: number }
        }
      }>('/api/resellers', {
        page,
        limit: 15,
      })

      if (res.success && res.data) {
        setResellers(res.data.resellers)
        setTotalPages(res.data.pagination.totalPages)

        // Compute summary from all resellers
        const allResellers = res.data.resellers
        const totalResellers = res.data.pagination.total
        const totalCommissionPaid = allResellers.reduce((sum, r) => sum + (r.paidCommission || 0), 0)
        const pendingPayouts = allResellers.reduce((sum, r) => sum + (r.pendingCommission || 0), 0)
        // Estimate this month (approx 1/3 of total for demo)
        const thisMonthEarnings = allResellers.reduce((sum, r) => sum + (r.totalCommission || 0), 0)

        setSummary({
          totalResellers,
          totalCommissionPaid,
          pendingPayouts,
          thisMonthEarnings,
        })
      } else {
        setError(res.error || 'Failed to load resellers')
      }
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setLoading(false)
    }
  }, [page])

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

  const handleViewReseller = async (reseller: Reseller) => {
    try {
      setDetailLoading(true)
      setSelectedReseller(null)
      setDetailOpen(true)
      const res = await api.get<{ success: boolean; data: ResellerDetail }>(`/api/resellers/${reseller.id}`)
      if (res.success && res.data) {
        setSelectedReseller(res.data)
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to load reseller details', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to load reseller details', variant: 'destructive' })
    } finally {
      setDetailLoading(false)
    }
  }

  const openEditDialog = (reseller: Reseller) => {
    setEditReseller(reseller)
    setEditCommissionType(reseller.commissionType)
    setEditCommissionValue(String(reseller.commissionValue))
    setEditOpen(true)
  }

  const handleSaveCommission = async () => {
    if (!editReseller) return
    const value = parseFloat(editCommissionValue)
    if (isNaN(value) || value < 0) {
      toast({ title: 'Validation Error', description: 'Please enter a valid commission value', variant: 'destructive' })
      return
    }
    try {
      setSaving(true)
      const res = await api.put<{ success: boolean; message?: string }>(`/api/resellers/${editReseller.id}`, {
        commissionType: editCommissionType,
        commissionValue: value,
      })
      if (res.success) {
        toast({ title: 'Success', description: 'Commission settings updated successfully.' })
        setEditOpen(false)
        fetchResellers()
        // Refresh detail if open
        if (selectedReseller?.id === editReseller.id) {
          const detailRes = await api.get<{ success: boolean; data: ResellerDetail }>(`/api/resellers/${editReseller.id}`)
          if (detailRes.success && detailRes.data) {
            setSelectedReseller(detailRes.data)
          }
        }
      } else {
        toast({ title: 'Error', description: res.error || 'Failed to update commission', variant: 'destructive' })
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to update commission', variant: 'destructive' })
    } finally {
      setSaving(false)
    }
  }

  const filteredResellers = resellers.filter((r) => {
    const matchesSearch =
      !searchQuery ||
      r.user?.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.user?.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      r.user?.phone.toLowerCase().includes(searchQuery.toLowerCase())

    const matchesStatus =
      statusFilter === 'all' ||
      (statusFilter === 'active' && r.isActive) ||
      (statusFilter === 'inactive' && !r.isActive)

    return matchesSearch && matchesStatus
  })

  return (
    <div className="space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight md:text-3xl">Resellers</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Manage reseller commissions and payouts
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchResellers}>
          <RefreshCcw className="size-4" />
          <span className="hidden sm:inline">Refresh</span>
        </Button>
      </div>

      {/* Summary Cards */}
      {loading && !summary ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <Card key={i} className="gap-4">
              <CardHeader className="flex flex-row items-center justify-between pb-0">
                <Skeleton className="h-4 w-28" />
                <Skeleton className="size-8 rounded-full" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-8 w-20" />
              </CardContent>
            </Card>
          ))}
        </div>
      ) : summary ? (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Total Resellers</CardTitle>
              <div className="bg-sky-100 dark:bg-sky-900/30 rounded-full p-2">
                <Users className="size-4 text-sky-600 dark:text-sky-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{summary.totalResellers}</div>
              <p className="text-xs text-muted-foreground mt-1">Registered resellers</p>
            </CardContent>
          </Card>

          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Commission Paid</CardTitle>
              <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-2">
                <TrendingUp className="size-4 text-emerald-600 dark:text-emerald-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(summary.totalCommissionPaid)}</div>
              <p className="text-xs text-muted-foreground mt-1">Total paid out</p>
            </CardContent>
          </Card>

          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Pending Payouts</CardTitle>
              <div className="bg-amber-100 dark:bg-amber-900/30 rounded-full p-2">
                <Clock className="size-4 text-amber-600 dark:text-amber-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(summary.pendingPayouts)}</div>
              <p className="text-xs text-muted-foreground mt-1">Awaiting payout</p>
            </CardContent>
          </Card>

          <Card className="gap-4">
            <CardHeader className="flex flex-row items-center justify-between pb-0">
              <CardTitle className="text-sm font-medium text-muted-foreground">Total Earnings</CardTitle>
              <div className="bg-purple-100 dark:bg-purple-900/30 rounded-full p-2">
                <Wallet className="size-4 text-purple-600 dark:text-purple-400" />
              </div>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(summary.thisMonthEarnings)}</div>
              <p className="text-xs text-muted-foreground mt-1">All-time commissions</p>
            </CardContent>
          </Card>
        </div>
      ) : null}

      {/* Filter Bar */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:flex-wrap">
            <div className="flex-1 min-w-[200px]">
              <Label className="text-xs mb-1.5 block">Search</Label>
              <div className="relative">
                <Search className="absolute left-2.5 top-2.5 size-4 text-muted-foreground" />
                <Input
                  placeholder="Name, email, phone..."
                  className="pl-9"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>

            <div className="w-full sm:w-[160px]">
              <Label className="text-xs mb-1.5 block">Status</Label>
              <Select value={statusFilter} onValueChange={(v) => { setStatusFilter(v); setPage(1) }}>
                <SelectTrigger className="w-full">
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="inactive">Inactive</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Resellers Table */}
      <Card>
        <CardContent className="p-0">
          {error ? (
            <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
              <XCircle className="size-10 mb-2 opacity-40" />
              <p className="font-medium">{error}</p>
              <Button variant="outline" size="sm" className="mt-3" onClick={fetchResellers}>
                <RefreshCcw className="size-4" />
                Retry
              </Button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead className="hidden md:table-cell">Email</TableHead>
                    <TableHead className="hidden lg:table-cell">Phone</TableHead>
                    <TableHead>Commission</TableHead>
                    <TableHead className="hidden sm:table-cell">Wallet</TableHead>
                    <TableHead className="hidden sm:table-cell">Total Earned</TableHead>
                    <TableHead className="hidden lg:table-cell">Clients</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    [...Array(6)].map((_, i) => (
                      <TableRow key={i}>
                        {[...Array(9)].map((_, j) => (
                          <TableCell key={j}>
                            <Skeleton className="h-4 w-full" />
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : filteredResellers.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={9} className="text-center py-12 text-muted-foreground">
                        <Users className="size-10 mx-auto mb-2 opacity-40" />
                        <p>No resellers found</p>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredResellers.map((reseller) => (
                      <TableRow key={reseller.id}>
                        <TableCell>
                          <div className="font-medium">{reseller.user?.name || 'Unknown'}</div>
                        </TableCell>
                        <TableCell className="hidden md:table-cell text-sm text-muted-foreground">
                          {reseller.user?.email}
                        </TableCell>
                        <TableCell className="hidden lg:table-cell text-sm text-muted-foreground">
                          {reseller.user?.phone || '-'}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1.5">
                            <Badge variant="secondary" className="bg-slate-100 text-slate-800 dark:bg-slate-800/40 dark:text-slate-300">
                              {reseller.commissionType === 'PERCENTAGE' ? '%' : '৳'}
                            </Badge>
                            <span className="text-sm font-medium">
                              {reseller.commissionType === 'PERCENTAGE'
                                ? `${reseller.commissionValue}%`
                                : formatCurrency(reseller.commissionValue)}
                            </span>
                          </div>
                        </TableCell>
                        <TableCell className="hidden sm:table-cell text-sm font-medium">
                          {formatCurrency(reseller.walletBalance)}
                        </TableCell>
                        <TableCell className="hidden sm:table-cell text-sm font-medium">
                          {formatCurrency(reseller.totalEarned)}
                        </TableCell>
                        <TableCell className="hidden lg:table-cell text-sm">
                          {reseller._count?.clients || 0}
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant="secondary"
                            className={
                              reseller.isActive
                                ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400'
                                : 'bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400'
                            }
                          >
                            <span
                              className={`mr-1 inline-block size-1.5 rounded-full ${
                                reseller.isActive ? 'bg-emerald-500' : 'bg-gray-400'
                              }`}
                            />
                            {reseller.isActive ? 'Active' : 'Inactive'}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-1">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewReseller(reseller)}
                            >
                              <Eye className="size-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => openEditDialog(reseller)}
                            >
                              <Edit3 className="size-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t px-4 py-3">
            <p className="text-sm text-muted-foreground">
              Page {page} of {totalPages}
            </p>
            <div className="flex gap-1">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                <ChevronLeft className="size-4" />
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                Next
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        )}
      </Card>

      {/* Reseller Detail Dialog */}
      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Users className="size-5" />
              Reseller Details
            </DialogTitle>
            <DialogDescription>
              {selectedReseller
                ? `${selectedReseller.user?.name} - ${selectedReseller.user?.email}`
                : 'Loading...'}
            </DialogDescription>
          </DialogHeader>

          {detailLoading && !selectedReseller ? (
            <div className="flex-1 space-y-4 p-4">
              <Skeleton className="h-6 w-3/4" />
              <Skeleton className="h-4 w-1/2" />
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
              <Skeleton className="h-20 w-full" />
            </div>
          ) : selectedReseller ? (
            <ScrollArea className="flex-1 px-1">
              <div className="space-y-6 pb-4">
                {/* Profile Info & Status */}
                <div className="flex flex-wrap items-center gap-2">
                  <Badge
                    variant="secondary"
                    className={
                      selectedReseller.isActive
                        ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400'
                        : 'bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400'
                    }
                  >
                    <span
                      className={`mr-1 inline-block size-1.5 rounded-full ${
                        selectedReseller.isActive ? 'bg-emerald-500' : 'bg-gray-400'
                      }`}
                    />
                    {selectedReseller.isActive ? 'Active' : 'Inactive'}
                  </Badge>
                  <span className="text-sm text-muted-foreground">
                    Joined {formatDate(selectedReseller.createdAt)}
                  </span>
                </div>

                {/* Profile Details */}
                <div>
                  <h3 className="text-sm font-semibold mb-2">Profile Information</h3>
                  <div className="rounded-lg border p-4">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                      <div className="flex items-center gap-2">
                        <Users className="size-4 text-muted-foreground" />
                        <div>
                          <span className="text-muted-foreground text-xs block">Name</span>
                          <span className="font-medium">{selectedReseller.user?.name}</span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Mail className="size-4 text-muted-foreground" />
                        <div>
                          <span className="text-muted-foreground text-xs block">Email</span>
                          <span className="font-medium">{selectedReseller.user?.email}</span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Phone className="size-4 text-muted-foreground" />
                        <div>
                          <span className="text-muted-foreground text-xs block">Phone</span>
                          <span className="font-medium">{selectedReseller.user?.phone || 'N/A'}</span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Calendar className="size-4 text-muted-foreground" />
                        <div>
                          <span className="text-muted-foreground text-xs block">Joined</span>
                          <span className="font-medium">{formatDate(selectedReseller.createdAt)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Commission Settings */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="text-sm font-semibold flex items-center gap-2">
                      <SlidersHorizontal className="size-4" />
                      Commission Settings
                    </h3>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => openEditDialog(selectedReseller)}
                    >
                      <Edit3 className="size-4" />
                      Edit
                    </Button>
                  </div>
                  <div className="rounded-lg border p-4">
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground text-xs block">Type</span>
                        <span className="font-medium">
                          {selectedReseller.commissionType === 'PERCENTAGE' ? 'Percentage' : 'Fixed'}
                        </span>
                      </div>
                      <div>
                        <span className="text-muted-foreground text-xs block">Value</span>
                        <span className="font-medium">
                          {selectedReseller.commissionType === 'PERCENTAGE'
                            ? `${selectedReseller.commissionValue}%`
                            : formatCurrency(selectedReseller.commissionValue)}
                        </span>
                      </div>
                      <div>
                        <span className="text-muted-foreground text-xs block">Total Earned</span>
                        <span className="font-medium">{formatCurrency(selectedReseller.totalEarned)}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground text-xs block">Wallet Balance</span>
                        <span className="font-medium">{formatCurrency(selectedReseller.walletBalance)}</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Wallet & Stats */}
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  <div className="rounded-lg border p-3 text-center">
                    <div className="text-xs text-muted-foreground">Active Clients</div>
                    <div className="text-lg font-bold mt-1">{selectedReseller._count?.clients || 0}</div>
                  </div>
                  <div className="rounded-lg border p-3 text-center">
                    <div className="text-xs text-muted-foreground">Total Commissions</div>
                    <div className="text-lg font-bold mt-1">{selectedReseller.commissions?.length || 0}</div>
                  </div>
                  <div className="rounded-lg border p-3 text-center">
                    <div className="text-xs text-muted-foreground">Pending</div>
                    <div className="text-lg font-bold mt-1 text-amber-600">
                      {formatCurrency(
                        selectedReseller.commissionBreakdown
                          ?.find((b) => b.status === 'PENDING')
                          ?._sum?.amount || 0
                      )}
                    </div>
                  </div>
                  <div className="rounded-lg border p-3 text-center">
                    <div className="text-xs text-muted-foreground">Paid</div>
                    <div className="text-lg font-bold mt-1 text-emerald-600">
                      {formatCurrency(
                        selectedReseller.commissionBreakdown
                          ?.find((b) => b.status === 'PAID')
                          ?._sum?.amount || 0
                      )}
                    </div>
                  </div>
                </div>

                <Separator />

                {/* Commission History */}
                <div>
                  <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
                    <DollarSign className="size-4" />
                    Commission History
                  </h3>
                  {selectedReseller.commissions && selectedReseller.commissions.length > 0 ? (
                    <div className="rounded-lg border overflow-hidden">
                      <div className="overflow-x-auto">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>Date</TableHead>
                              <TableHead>Client</TableHead>
                              <TableHead className="hidden sm:table-cell">Invoice</TableHead>
                              <TableHead className="text-right">Amount</TableHead>
                              <TableHead>Status</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {selectedReseller.commissions.map((commission) => (
                              <TableRow key={commission.id}>
                                <TableCell className="text-sm">
                                  {formatDate(commission.createdAt)}
                                </TableCell>
                                <TableCell className="text-sm font-medium">
                                  {commission.user?.name || 'Unknown'}
                                </TableCell>
                                <TableCell className="hidden sm:table-cell font-mono text-xs text-muted-foreground">
                                  {commission.invoice?.invoiceNumber || '-'}
                                </TableCell>
                                <TableCell className="text-right text-sm font-medium">
                                  {formatCurrency(commission.amount)}
                                </TableCell>
                                <TableCell>
                                  <Badge
                                    variant="secondary"
                                    className={statusBadgeColors[commission.status] || ''}
                                  >
                                    {commission.status}
                                  </Badge>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground text-center py-6">
                      No commission history yet.
                    </p>
                  )}
                </div>

                <Separator />

                {/* Transaction History */}
                <div>
                  <h3 className="text-sm font-semibold mb-2 flex items-center gap-2">
                    <Wallet className="size-4" />
                    Transaction History
                  </h3>
                  {selectedReseller.transactions && selectedReseller.transactions.length > 0 ? (
                    <div className="rounded-lg border overflow-hidden">
                      <div className="overflow-x-auto">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>Date</TableHead>
                              <TableHead>Type</TableHead>
                              <TableHead>Description</TableHead>
                              <TableHead className="text-right">Amount</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {selectedReseller.transactions.map((txn) => (
                              <TableRow key={txn.id}>
                                <TableCell className="text-sm">
                                  {formatDate(txn.createdAt)}
                                </TableCell>
                                <TableCell>
                                  <Badge
                                    variant="secondary"
                                    className={transactionTypeBadge[txn.type] || ''}
                                  >
                                    {txn.type === 'COMMISSION' ? (
                                      <ArrowDownLeft className="size-3 mr-1" />
                                    ) : txn.type === 'WITHDRAWAL' ? (
                                      <ArrowUpRight className="size-3 mr-1" />
                                    ) : null}
                                    {txn.type}
                                  </Badge>
                                </TableCell>
                                <TableCell className="text-sm text-muted-foreground max-w-[200px] truncate">
                                  {txn.description || '-'}
                                </TableCell>
                                <TableCell
                                  className={`text-right text-sm font-medium ${
                                    txn.type === 'COMMISSION'
                                      ? 'text-emerald-600'
                                      : txn.type === 'WITHDRAWAL'
                                      ? 'text-red-600'
                                      : ''
                                  }`}
                                >
                                  {txn.type === 'COMMISSION' ? '+' : txn.type === 'WITHDRAWAL' ? '-' : ''}
                                  {formatCurrency(txn.amount)}
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </div>
                  ) : (
                    <p className="text-sm text-muted-foreground text-center py-6">
                      No transactions yet.
                    </p>
                  )}
                </div>
              </div>
            </ScrollArea>
          ) : null}
        </DialogContent>
      </Dialog>

      {/* Edit Commission Dialog */}
      <Dialog open={editOpen} onOpenChange={setEditOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit3 className="size-5" />
              Edit Commission
            </DialogTitle>
            <DialogDescription>
              {editReseller
                ? `Update commission settings for ${editReseller.user?.name}`
                : ''}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>Commission Type</Label>
              <Select
                value={editCommissionType}
                onValueChange={setEditCommissionType}
              >
                <SelectTrigger className="w-full mt-1.5">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PERCENTAGE">Percentage (%)</SelectItem>
                  <SelectItem value="FIXED">Fixed Amount (৳)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>
                {editCommissionType === 'PERCENTAGE' ? 'Commission Percentage' : 'Fixed Commission Amount (৳)'}
              </Label>
              <div className="relative mt-1.5">
                <span className="absolute left-3 top-2.5 text-sm text-muted-foreground">
                  {editCommissionType === 'PERCENTAGE' ? '%' : '৳'}
                </span>
                <Input
                  type="number"
                  step="0.01"
                  min="0"
                  className="pl-8"
                  placeholder={editCommissionType === 'PERCENTAGE' ? '0' : '0'}
                  value={editCommissionValue}
                  onChange={(e) => setEditCommissionValue(e.target.value)}
                />
              </div>
              {editCommissionType === 'PERCENTAGE' && editCommissionValue && parseFloat(editCommissionValue) > 100 && (
                <p className="text-xs text-red-500 mt-1">Percentage cannot exceed 100%</p>
              )}
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setEditOpen(false)}>
              Cancel
            </Button>
            <Button
              onClick={handleSaveCommission}
              disabled={saving || !editCommissionValue || parseFloat(editCommissionValue) < 0 || (editCommissionType === 'PERCENTAGE' && parseFloat(editCommissionValue) > 100)}
            >
              {saving ? <Loader2 className="size-4 animate-spin" /> : <SlidersHorizontal className="size-4" />}
              Save Changes
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
