'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  BarChart3,
  Download,
  TrendingUp,
  TrendingDown,
  DollarSign,
  Users,
  PieChart as PieChartIcon,
  Loader2,
  AlertTriangle,
  FileBarChart,
  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 { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from '@/components/ui/chart'
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
} from 'recharts'
import { api } from '@/lib/api'

// ---- Types ----
interface AreaReportData {
  areas: Array<{
    id: string
    name: string
    totalClients: number
    activeClients: number
    totalBilled: number
    totalCollected: number
    dueAmount: number
    collectionRate: number
  }>
  summary: {
    totalRevenue: number
    totalCollected: number
    totalDue: number
    collectionRate: number
  }
}

interface RevenueData {
  month: string
  year: number
  revenue: number
  invoices: number
}

interface GrowthData {
  month: string
  year: number
  total: number
  active: number
  expired: number
  newUsers: number
}

interface DashboardStats {
  users: {
    total: number
    active: number
    expired: number
    suspended: number
    pending: number
    byStatus: Record<string, number>
  }
  revenue: {
    total: number
    totalBilled: number
    thisMonth: number
    unpaid: number
  }
}

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

// ---- Chart Configs ----
const areaChartConfig: ChartConfig = {
  totalBilled: { label: 'Total Billed', color: 'hsl(var(--chart-1))' },
  totalCollected: { label: 'Total Collected', color: 'hsl(var(--chart-2))' },
  dueAmount: { label: 'Due Amount', color: 'hsl(var(--chart-5))' },
}

const revenueLineConfig: ChartConfig = {
  revenue: { label: 'Revenue (BDT)', color: 'hsl(var(--chart-1))' },
  invoices: { label: 'Invoices', color: 'hsl(var(--chart-3))' },
}

const statusPieConfig: ChartConfig = {
  active: { label: 'Active', color: 'hsl(142 76% 36%)' },
  expired: { label: 'Expired', color: 'hsl(38 92% 50%)' },
  suspended: { label: 'Suspended', color: 'hsl(0 84% 60%)' },
  pending: { label: 'Pending', color: 'hsl(48 96% 53%)' },
}

const growthLineConfig: ChartConfig = {
  total: { label: 'Total', color: 'hsl(var(--chart-1))' },
  active: { label: 'Active', color: 'hsl(var(--chart-2))' },
  newUsers: { label: 'New Users', color: 'hsl(var(--chart-3))' },
}

const PIE_COLORS = ['#22c55e', '#f59e0b', '#ef4444', '#facc15']

// ---- Skeleton Components ----
function SummaryCardSkeleton() {
  return (
    <Card className="p-4">
      <div className="flex items-center gap-4">
        <Skeleton className="size-10 rounded-lg" />
        <div className="flex-1 space-y-2">
          <Skeleton className="h-4 w-24" />
          <Skeleton className="h-7 w-20" />
        </div>
      </div>
    </Card>
  )
}

function ChartSkeleton() {
  return (
    <Card>
      <CardHeader>
        <Skeleton className="h-5 w-40" />
        <Skeleton className="h-4 w-56" />
      </CardHeader>
      <CardContent>
        <Skeleton className="h-[300px] w-full" />
      </CardContent>
    </Card>
  )
}

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

// ---- CSV Export ----
function exportCSV(filename: string, headers: string[], rows: string[][]) {
  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 = `${filename}-${new Date().toISOString().split('T')[0]}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

// ---- Main Component ----
export default function ReportsView() {
  // Area Report state
  const [areaData, setAreaData] = useState<AreaReportData | null>(null)
  const [revenueData, setRevenueData] = useState<RevenueData[]>([])
  const [growthData, setGrowthData] = useState<GrowthData[]>([])
  const [stats, setStats] = useState<DashboardStats | null>(null)

  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState('area')

  const fetchData = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const [areaRes, revenueRes, growthRes, statsRes] = await Promise.all([
        api.get<AreaReportData>('/api/reports/area'),
        api.get<{ data: RevenueData[] }>('/api/dashboard/revenue', { period: 'monthly', months: 12 }),
        api.get<{ data: GrowthData[] }>('/api/dashboard/growth', { months: 6 }),
        api.get<DashboardStats>('/api/dashboard/stats'),
      ])

      if (areaRes.success && areaRes.data) setAreaData(areaRes.data)
      if (revenueRes.success && revenueRes.data) setRevenueData(revenueRes.data.data || [])
      if (growthRes.success && growthRes.data) setGrowthData(growthRes.data.data || [])
      if (statsRes.success && statsRes.data) setStats(statsRes.data)
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Failed to load reports'
      setError(message)
    } finally {
      setLoading(false)
    }
  }, [])

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

  // ---- Area Report Data ----
  const areaChartData = (areaData?.areas || []).map((a) => ({
    name: a.name,
    totalBilled: a.totalBilled,
    totalCollected: a.totalCollected,
    dueAmount: a.dueAmount,
  }))

  const revenueChartData = revenueData.map((d) => ({
    label: `${d.month} ${d.year}`,
    revenue: d.revenue,
    invoices: d.invoices,
  }))

  const growthChartData = growthData.map((d) => ({
    label: `${d.month} ${d.year}`,
    total: d.total,
    active: d.active,
    newUsers: d.newUsers,
  }))

  // Client distribution by status for pie chart
  const statusPieData = stats
    ? [
        { name: 'active', value: stats.users.active },
        { name: 'expired', value: stats.users.expired },
        { name: 'suspended', value: stats.users.suspended },
        { name: 'pending', value: stats.users.pending },
      ].filter((d) => d.value > 0)
    : []

  // Client distribution by area for bar chart (from area data)
  const areaBarData = (areaData?.areas || []).map((a) => ({
    name: a.name,
    total: a.totalClients,
    active: a.activeClients,
  }))

  // Revenue growth calc
  const revenueGrowth =
    revenueData.length >= 2
      ? (() => {
          const prev = revenueData[revenueData.length - 2].revenue
          const curr = revenueData[revenueData.length - 1].revenue
          return prev > 0 ? ((curr - prev) / prev) * 100 : 0
        })()
      : 0

  // Export handlers
  const handleExportArea = () => {
    if (!areaData) return
    const headers = ['Area Name', 'Total Clients', 'Active Clients', 'Total Billed', 'Total Collected', 'Due Amount', 'Collection Rate']
    const rows = areaData.areas.map((a) => [
      a.name, String(a.totalClients), String(a.activeClients),
      String(a.totalBilled), String(a.totalCollected),
      String(a.dueAmount), `${a.collectionRate.toFixed(1)}%`,
    ])
    exportCSV('area-report', headers, rows)
  }

  const handleExportRevenue = () => {
    const headers = ['Month', 'Year', 'Revenue', 'Invoices']
    const rows = revenueData.map((d) => [d.month, String(d.year), String(d.revenue), String(d.invoices)])
    exportCSV('revenue-report', headers, rows)
  }

  const handleExportClient = () => {
    if (!stats) return
    const headers = ['Status', 'Count']
    const rows = Object.entries(stats.users.byStatus).map(([k, v]) => [k, String(v)])
    exportCSV('client-report', headers, rows)
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4">
        <AlertTriangle className="size-12 text-destructive" />
        <p className="text-muted-foreground text-center">{error}</p>
        <Button onClick={fetchData} variant="outline">
          Retry
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6 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">Reports</h1>
          <p className="text-muted-foreground mt-1">
            Area-wise billing reports, revenue analysis, and client insights
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            if (activeTab === 'area') handleExportArea()
            else if (activeTab === 'revenue') handleExportRevenue()
            else handleExportClient()
          }}
          disabled={loading}
        >
          <Download className="size-4" />
          Export CSV
        </Button>
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList>
          <TabsTrigger value="area" className="gap-1.5">
            <BarChart3 className="size-3.5" />
            Area Report
          </TabsTrigger>
          <TabsTrigger value="revenue" className="gap-1.5">
            <DollarSign className="size-3.5" />
            Revenue Report
          </TabsTrigger>
          <TabsTrigger value="client" className="gap-1.5">
            <Users className="size-3.5" />
            Client Report
          </TabsTrigger>
        </TabsList>

        {/* ===== Area Report Tab ===== */}
        <TabsContent value="area" className="mt-6 space-y-6">
          {/* Summary Cards */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {loading ? (
              Array.from({ length: 4 }).map((_, i) => <SummaryCardSkeleton key={i} />)
            ) : (
              <>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                      <DollarSign className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Total Revenue</p>
                      <p className="text-lg font-bold truncate">{formatCurrency(areaData?.summary.totalRevenue || 0)}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-teal-100 text-teal-600 dark:bg-teal-900/30 dark:text-teal-400">
                      <TrendingUp className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Total Collected</p>
                      <p className="text-lg font-bold truncate">{formatCurrency(areaData?.summary.totalCollected || 0)}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400">
                      <TrendingDown className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Total Due</p>
                      <p className="text-lg font-bold truncate">{formatCurrency(areaData?.summary.totalDue || 0)}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-violet-100 text-violet-600 dark:bg-violet-900/30 dark:text-violet-400">
                      <FileBarChart className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Collection Rate</p>
                      <p className="text-lg font-bold truncate">{(areaData?.summary.collectionRate || 0).toFixed(1)}%</p>
                    </div>
                  </div>
                </Card>
              </>
            )}
          </div>

          {/* Area Revenue Bar Chart */}
          {loading ? (
            <ChartSkeleton />
          ) : (
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Area Revenue Comparison</CardTitle>
                <CardDescription>Billed vs Collected vs Due by area</CardDescription>
              </CardHeader>
              <CardContent>
                {areaChartData.length > 0 ? (
                  <ChartContainer config={areaChartConfig} className="h-[350px] w-full">
                    <BarChart data={areaChartData} margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                      <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                      <XAxis dataKey="name" tickLine={false} axisLine={false} tickMargin={8} className="text-xs" />
                      <YAxis
                        tickLine={false}
                        axisLine={false}
                        tickMargin={8}
                        tickFormatter={(v: number) => `৳${(v / 1000).toFixed(0)}k`}
                        className="text-xs"
                      />
                      <ChartTooltip content={<ChartTooltipContent />} />
                      <Bar dataKey="totalBilled" fill="hsl(var(--chart-1))" radius={[4, 4, 0, 0]} maxBarSize={32} />
                      <Bar dataKey="totalCollected" fill="hsl(var(--chart-2))" radius={[4, 4, 0, 0]} maxBarSize={32} />
                      <Bar dataKey="dueAmount" fill="hsl(var(--chart-5))" radius={[4, 4, 0, 0]} maxBarSize={32} />
                    </BarChart>
                  </ChartContainer>
                ) : (
                  <div className="flex items-center justify-center h-[300px] text-muted-foreground">
                    No area data available
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Area-wise Table */}
          {loading ? (
            <TableSkeleton />
          ) : (
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Area-wise Billing Details</CardTitle>
                <CardDescription>Detailed billing breakdown by area</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="max-h-96 overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Area Name</TableHead>
                        <TableHead className="text-right">Total Clients</TableHead>
                        <TableHead className="text-right hidden sm:table-cell">Active Clients</TableHead>
                        <TableHead className="text-right">Total Billed</TableHead>
                        <TableHead className="text-right hidden md:table-cell">Total Collected</TableHead>
                        <TableHead className="text-right hidden lg:table-cell">Due Amount</TableHead>
                        <TableHead className="text-right">Collection Rate</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {(areaData?.areas || []).length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={7} className="h-24 text-center text-muted-foreground">
                            No area data available
                          </TableCell>
                        </TableRow>
                      ) : (
                        areaData?.areas.map((area) => (
                          <TableRow key={area.id}>
                            <TableCell className="font-medium">{area.name}</TableCell>
                            <TableCell className="text-right">{area.totalClients}</TableCell>
                            <TableCell className="text-right hidden sm:table-cell">{area.activeClients}</TableCell>
                            <TableCell className="text-right font-medium">{formatCurrency(area.totalBilled)}</TableCell>
                            <TableCell className="text-right hidden md:table-cell">{formatCurrency(area.totalCollected)}</TableCell>
                            <TableCell className="text-right hidden lg:table-cell text-red-600 dark:text-red-400">
                              {formatCurrency(area.dueAmount)}
                            </TableCell>
                            <TableCell className="text-right">
                              <Badge
                                variant="secondary"
                                className={
                                  area.collectionRate >= 80
                                    ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                                    : area.collectionRate >= 50
                                      ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'
                                      : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                                }
                              >
                                {area.collectionRate.toFixed(1)}%
                              </Badge>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* ===== Revenue Report Tab ===== */}
        <TabsContent value="revenue" className="mt-6 space-y-6">
          {/* Monthly Revenue Summary Cards */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {loading ? (
              Array.from({ length: 4 }).map((_, i) => <SummaryCardSkeleton key={i} />)
            ) : (
              <>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                      <DollarSign className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Total Revenue</p>
                      <p className="text-lg font-bold truncate">{formatCurrency(stats?.revenue.total || 0)}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-teal-100 text-teal-600 dark:bg-teal-900/30 dark:text-teal-400">
                      <Activity className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">This Month</p>
                      <p className="text-lg font-bold truncate">{formatCurrency(stats?.revenue.thisMonth || 0)}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400">
                      <TrendingDown className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Unpaid</p>
                      <p className="text-lg font-bold truncate">{formatCurrency(stats?.revenue.unpaid || 0)}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-violet-100 text-violet-600 dark:bg-violet-900/30 dark:text-violet-400">
                      {revenueGrowth >= 0 ? <TrendingUp className="size-5" /> : <TrendingDown className="size-5" />}
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Revenue Growth</p>
                      <p className={`text-lg font-bold truncate ${revenueGrowth >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
                        {revenueGrowth >= 0 ? '+' : ''}{revenueGrowth.toFixed(1)}%
                      </p>
                    </div>
                  </div>
                </Card>
              </>
            )}
          </div>

          {/* Revenue Line Chart */}
          {loading ? (
            <ChartSkeleton />
          ) : (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-base">Revenue Trend</CardTitle>
                    <CardDescription>Monthly revenue for the last 12 months</CardDescription>
                  </div>
                  <Badge variant="secondary" className="flex items-center gap-1">
                    {revenueGrowth >= 0 ? <TrendingUp className="size-3 text-emerald-500" /> : <TrendingDown className="size-3 text-red-500" />}
                    {revenueGrowth >= 0 ? '+' : ''}{revenueGrowth.toFixed(1)}%
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                {revenueChartData.length > 0 ? (
                  <ChartContainer config={revenueLineConfig} className="h-[350px] w-full">
                    <LineChart data={revenueChartData} margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                      <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                      <XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} className="text-xs" />
                      <YAxis
                        tickLine={false}
                        axisLine={false}
                        tickMargin={8}
                        tickFormatter={(v: number) => `৳${(v / 1000).toFixed(0)}k`}
                        className="text-xs"
                      />
                      <ChartTooltip content={<ChartTooltipContent />} />
                      <Line type="monotone" dataKey="revenue" stroke="hsl(var(--chart-1))" strokeWidth={2} dot={false} activeDot={{ r: 4 }} />
                    </LineChart>
                  </ChartContainer>
                ) : (
                  <div className="flex items-center justify-center h-[300px] text-muted-foreground">
                    No revenue data available
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Monthly Comparison Table */}
          {loading ? (
            <TableSkeleton />
          ) : (
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Monthly Comparison</CardTitle>
                <CardDescription>Revenue and invoice count by month</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="max-h-96 overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Month</TableHead>
                        <TableHead className="text-right">Revenue</TableHead>
                        <TableHead className="text-right">Invoices</TableHead>
                        <TableHead className="text-right hidden sm:table-cell">Avg per Invoice</TableHead>
                        <TableHead className="hidden md:table-cell">Trend</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {revenueData.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
                            No revenue data available
                          </TableCell>
                        </TableRow>
                      ) : (
                        [...revenueData].reverse().map((d, i) => {
                          const prevRevenue = i < revenueData.length - 1 ? revenueData[revenueData.length - 1 - i - 1].revenue : null
                          const change = prevRevenue && prevRevenue > 0 ? ((d.revenue - prevRevenue) / prevRevenue) * 100 : null
                          return (
                            <TableRow key={`${d.month}-${d.year}`}>
                              <TableCell className="font-medium">{d.month} {d.year}</TableCell>
                              <TableCell className="text-right font-medium">{formatCurrency(d.revenue)}</TableCell>
                              <TableCell className="text-right">{d.invoices}</TableCell>
                              <TableCell className="text-right hidden sm:table-cell">
                                {d.invoices > 0 ? formatCurrency(Math.round(d.revenue / d.invoices)) : 'N/A'}
                              </TableCell>
                              <TableCell className="hidden md:table-cell">
                                {change !== null ? (
                                  <Badge
                                    variant="secondary"
                                    className={
                                      change >= 0
                                        ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                                        : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                                    }
                                  >
                                    {change >= 0 ? <TrendingUp className="size-3 mr-1" /> : <TrendingDown className="size-3 mr-1" />}
                                    {change >= 0 ? '+' : ''}{change.toFixed(1)}%
                                  </Badge>
                                ) : (
                                  <span className="text-muted-foreground text-xs">N/A</span>
                                )}
                              </TableCell>
                            </TableRow>
                          )
                        })
                      )}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        {/* ===== Client Report Tab ===== */}
        <TabsContent value="client" className="mt-6 space-y-6">
          {/* Summary */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {loading ? (
              Array.from({ length: 4 }).map((_, i) => <SummaryCardSkeleton key={i} />)
            ) : (
              <>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400">
                      <Users className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Total Clients</p>
                      <p className="text-lg font-bold truncate">{stats?.users.total || 0}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400">
                      <Activity className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Active Clients</p>
                      <p className="text-lg font-bold truncate">{stats?.users.active || 0}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400">
                      <AlertTriangle className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Expired Clients</p>
                      <p className="text-lg font-bold truncate">{stats?.users.expired || 0}</p>
                    </div>
                  </div>
                </Card>
                <Card className="p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex items-center justify-center size-10 rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400">
                      <TrendingDown className="size-5" />
                    </div>
                    <div className="min-w-0">
                      <p className="text-xs text-muted-foreground font-medium">Suspended</p>
                      <p className="text-lg font-bold truncate">{stats?.users.suspended || 0}</p>
                    </div>
                  </div>
                </Card>
              </>
            )}
          </div>

          {/* Charts Row */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Client Status Pie Chart */}
            {loading ? (
              <ChartSkeleton />
            ) : (
              <Card>
                <CardHeader>
                  <div className="flex items-center gap-2">
                    <PieChartIcon className="size-4 text-muted-foreground" />
                    <CardTitle className="text-base">Client Distribution by Status</CardTitle>
                  </div>
                </CardHeader>
                <CardContent>
                  {statusPieData.length > 0 ? (
                    <ChartContainer config={statusPieConfig} className="h-[300px] w-full">
                      <PieChart>
                        <ChartTooltip content={<ChartTooltipContent />} />
                        <Pie
                          data={statusPieData}
                          cx="50%"
                          cy="50%"
                          innerRadius={60}
                          outerRadius={100}
                          dataKey="value"
                          nameKey="name"
                          label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                          labelLine={false}
                        >
                          {statusPieData.map((_, index) => (
                            <Cell key={index} fill={PIE_COLORS[index % PIE_COLORS.length]} />
                          ))}
                        </Pie>
                      </PieChart>
                    </ChartContainer>
                  ) : (
                    <div className="flex items-center justify-center h-[260px] text-muted-foreground">
                      No client data available
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* Client Distribution by Area */}
            {loading ? (
              <ChartSkeleton />
            ) : (
              <Card>
                <CardHeader>
                  <CardTitle className="text-base">Client Distribution by Area</CardTitle>
                  <CardDescription>Total vs Active clients per area</CardDescription>
                </CardHeader>
                <CardContent>
                  {areaBarData.length > 0 ? (
                    <ChartContainer config={{ total: { label: 'Total', color: 'hsl(var(--chart-1))' }, active: { label: 'Active', color: 'hsl(var(--chart-2))' } }} className="h-[300px] w-full">
                      <BarChart data={areaBarData} layout="vertical" margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                        <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                        <XAxis type="number" tickLine={false} axisLine={false} tickMargin={8} className="text-xs" />
                        <YAxis type="category" dataKey="name" tickLine={false} axisLine={false} tickMargin={8} className="text-xs" width={80} />
                        <ChartTooltip content={<ChartTooltipContent />} />
                        <Bar dataKey="total" fill="hsl(var(--chart-1))" radius={[0, 4, 4, 0]} maxBarSize={20} />
                        <Bar dataKey="active" fill="hsl(var(--chart-2))" radius={[0, 4, 4, 0]} maxBarSize={20} />
                      </BarChart>
                    </ChartContainer>
                  ) : (
                    <div className="flex items-center justify-center h-[260px] text-muted-foreground">
                      No area data available
                    </div>
                  )}
                </CardContent>
              </Card>
            )}
          </div>

          {/* Client Growth Trend */}
          {loading ? (
            <ChartSkeleton />
          ) : (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-base">Client Growth Trend</CardTitle>
                    <CardDescription>Total, active, and new users over time</CardDescription>
                  </div>
                  <Badge variant="secondary" className="flex items-center gap-1">
                    <TrendingUp className="size-3 text-emerald-500" />
                    Growing
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                {growthChartData.length > 0 ? (
                  <ChartContainer config={growthLineConfig} className="h-[350px] w-full">
                    <AreaChart data={growthChartData} margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                      <defs>
                        <linearGradient id="totalGrad" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor="hsl(var(--chart-1))" stopOpacity={0.3} />
                          <stop offset="95%" stopColor="hsl(var(--chart-1))" stopOpacity={0} />
                        </linearGradient>
                        <linearGradient id="activeGrad" x1="0" y1="0" x2="0" y2="1">
                          <stop offset="5%" stopColor="hsl(var(--chart-2))" stopOpacity={0.3} />
                          <stop offset="95%" stopColor="hsl(var(--chart-2))" stopOpacity={0} />
                        </linearGradient>
                      </defs>
                      <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                      <XAxis dataKey="label" tickLine={false} axisLine={false} tickMargin={8} className="text-xs" />
                      <YAxis tickLine={false} axisLine={false} tickMargin={8} className="text-xs" />
                      <ChartTooltip content={<ChartTooltipContent />} />
                      <Area type="monotone" dataKey="total" stroke="hsl(var(--chart-1))" fill="url(#totalGrad)" strokeWidth={2} dot={false} />
                      <Area type="monotone" dataKey="active" stroke="hsl(var(--chart-2))" fill="url(#activeGrad)" strokeWidth={2} dot={false} />
                      <Line type="monotone" dataKey="newUsers" stroke="hsl(var(--chart-3))" strokeWidth={2} dot={{ r: 3 }} strokeDasharray="5 5" />
                    </AreaChart>
                  </ChartContainer>
                ) : (
                  <div className="flex items-center justify-center h-[300px] text-muted-foreground">
                    No growth data available
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  )
}
