'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Users,
  CheckCircle,
  AlertTriangle,
  DollarSign,
  Clock,
  Ban,
  HelpCircle,
  Wifi,
  XCircle,
  UserPlus,
  UserCheck,
  Activity,
  TrendingUp,
  TrendingDown,
  FileText,
  Plus,
  BarChart3,
  ArrowUpRight,
  ArrowDownRight,
} 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from '@/components/ui/chart'
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
} from 'recharts'
import { api } from '@/lib/api'
import { useAppStore } from '@/store/app-store'

// ---- Types ----
interface DashboardStats {
  users: {
    total: number
    active: number
    expired: number
    suspended: number
    pending: number
    byStatus: Record<string, number>
    byRole: Record<string, number>
  }
  subscriptions: {
    total: number
    active: number
    byStatus: Record<string, number>
  }
  revenue: {
    total: number
    totalBilled: number
    thisMonth: number
    thisMonthTransactions: number
    unpaid: number
  }
  invoices: {
    breakdown: Record<string, { count: number; amount: number }>
    dueOverdue: number
  }
  tickets: {
    total: number
    open: number
    byStatus: Record<string, number>
  }
  network: {
    onlineOLTs: number
    onus: Record<string, number>
    totalONUs: number
  }
  plans: { active: number }
  areas: { total: number }
  resellers: { total: number }
  recentInvoices: RecentInvoice[]
}

interface RecentInvoice {
  id: string
  invoiceNumber: string
  totalAmount: number
  paidAmount: number
  status: string
  dueDate: string
  createdAt: string
  user: { id: string; name: string }
}

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 RecentTicket {
  id: string
  subject: string
  status: string
  priority: string
  createdAt: string
  user: { id: string; name: string; email: string }
}

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

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

const ticketStatusColor: Record<string, string> = {
  OPEN: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  IN_PROGRESS: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  RESOLVED: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
  CLOSED: 'bg-gray-100 text-gray-600 dark:bg-gray-800/30 dark:text-gray-400',
}

const ticketPriorityColor: Record<string, string> = {
  LOW: 'bg-slate-100 text-slate-600 dark:bg-slate-800/30 dark:text-slate-400',
  MEDIUM: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  HIGH: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
  URGENT: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
}

// ---- Chart configs ----
const revenueChartConfig: ChartConfig = {
  revenue: {
    label: 'Revenue',
    color: 'hsl(var(--chart-1))',
  },
  invoices: {
    label: 'Invoices',
    color: 'hsl(var(--chart-2))',
  },
}

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

// ---- Skeleton Components ----
function StatsCardSkeleton() {
  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-16" />
          <Skeleton className="h-3 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-[280px] w-full" />
      </CardContent>
    </Card>
  )
}

// ---- Main Component ----
export default function DashboardView() {
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [revenueData, setRevenueData] = useState<RevenueData[]>([])
  const [growthData, setGrowthData] = useState<GrowthData[]>([])
  const [recentTickets, setRecentTickets] = useState<RecentTicket[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const setCurrentView = useAppStore((s) => s.setCurrentView)

  const fetchDashboard = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const [statsRes, revenueRes, growthRes, ticketsRes] = await Promise.all([
        api.get<DashboardStats>('/api/dashboard/stats'),
        api.get<{ data: RevenueData[] }>('/api/dashboard/revenue', { period: 'monthly', months: 6 }),
        api.get<{ data: GrowthData[] }>('/api/dashboard/growth', { months: 6 }),
        api.get<{ data: { tickets: RecentTicket[] } }>('/api/tickets', { limit: 5 }),
      ])

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

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

  // Revenue chart data with label
  const revenueChartData = revenueData.map((d) => ({
    ...d,
    label: `${d.month} ${d.year}`,
  }))

  // Growth chart data with label
  const growthChartData = growthData.map((d) => ({
    ...d,
    label: `${d.month} ${d.year}`,
  }))

  // Revenue growth calculation
  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

  const statsCards = stats
    ? [
        {
          icon: Users,
          label: 'Total Users',
          value: stats.users.total.toString(),
          sub: `${stats.users.active} active`,
          trend: '+12%',
          trendUp: true,
          iconBg: 'bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400',
        },
        {
          icon: CheckCircle,
          label: 'Active Clients',
          value: stats.users.active.toString(),
          sub: 'Currently active',
          trend: '+8%',
          trendUp: true,
          iconBg: 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400',
        },
        {
          icon: AlertTriangle,
          label: 'Expired Clients',
          value: stats.users.expired.toString(),
          sub: 'Need attention',
          trend: '-3%',
          trendUp: false,
          iconBg: 'bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400',
        },
        {
          icon: DollarSign,
          label: 'Monthly Revenue',
          value: formatCurrency(stats.revenue.thisMonth),
          sub: `${stats.revenue.thisMonthTransactions} transactions`,
          trend: `${revenueGrowth >= 0 ? '+' : ''}${revenueGrowth.toFixed(1)}%`,
          trendUp: revenueGrowth >= 0,
          iconBg: 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400',
        },
        {
          icon: Clock,
          label: 'Due Payments',
          value: stats.invoices.dueOverdue.toString(),
          sub: formatCurrency(stats.invoices.breakdown?.DUE?.amount || stats.revenue.unpaid),
          trend: `${stats.invoices.breakdown?.UNPAID?.count || 0} unpaid`,
          trendUp: false,
          iconBg: 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400',
        },
        {
          icon: Ban,
          label: 'Suspended Clients',
          value: stats.users.suspended.toString(),
          sub: 'Currently suspended',
          trend: '0%',
          trendUp: false,
          iconBg: 'bg-purple-100 text-purple-600 dark:bg-purple-900/30 dark:text-purple-400',
        },
        {
          icon: HelpCircle,
          label: 'Active Tickets',
          value: stats.tickets.open.toString(),
          sub: `of ${stats.tickets.total} total`,
          trend: stats.tickets.open > 5 ? 'Review' : 'Low',
          trendUp: stats.tickets.open <= 5,
          iconBg: 'bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400',
        },
        {
          icon: Wifi,
          label: 'Online Users',
          value: (stats.network.onus.ONLINE || 0).toString(),
          sub: `of ${stats.network.totalONUs} ONUs`,
          trend: `${Math.round(((stats.network.onus.ONLINE || 0) / Math.max(stats.network.totalONUs, 1)) * 100)}% online`,
          trendUp: true,
          iconBg: 'bg-cyan-100 text-cyan-600 dark:bg-cyan-900/30 dark:text-cyan-400',
        },
        {
          icon: XCircle,
          label: 'Closed Connections',
          value: (stats.network.onus.OFFLINE || 0).toString(),
          sub: 'Currently offline',
          trend: 'Monitor',
          trendUp: false,
          iconBg: 'bg-gray-100 text-gray-600 dark:bg-gray-800/30 dark:text-gray-400',
        },
        {
          icon: UserPlus,
          label: 'Pending Activations',
          value: stats.users.pending.toString(),
          sub: 'Awaiting setup',
          trend: 'Action needed',
          trendUp: true,
          iconBg: 'bg-teal-100 text-teal-600 dark:bg-teal-900/30 dark:text-teal-400',
        },
        {
          icon: UserCheck,
          label: 'New Registrations',
          value: growthData.length > 0 ? growthData[growthData.length - 1].newUsers.toString() : '0',
          sub: 'This month',
          trend: growthData.length >= 2
            ? `${growthData[growthData.length - 1].newUsers - growthData[growthData.length - 2].newUsers >= 0 ? '+' : ''}${growthData[growthData.length - 1].newUsers - growthData[growthData.length - 2].newUsers}`
            : 'N/A',
          trendUp: growthData.length >= 2 ? growthData[growthData.length - 1].newUsers >= growthData[growthData.length - 2].newUsers : true,
          iconBg: 'bg-violet-100 text-violet-600 dark:bg-violet-900/30 dark:text-violet-400',
        },
        {
          icon: Activity,
          label: 'System Uptime',
          value: '99.9%',
          sub: 'Last 30 days',
          trend: 'Healthy',
          trendUp: true,
          iconBg: 'bg-lime-100 text-lime-600 dark:bg-lime-900/30 dark:text-lime-400',
        },
      ]
    : []

  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={fetchDashboard} 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">Dashboard</h1>
          <p className="text-muted-foreground mt-1">
            Overview of your ISP billing and network management
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={fetchDashboard} disabled={loading}>
            <Activity className="size-4" />
            Refresh
          </Button>
        </div>
      </div>

      {/* Stats Cards Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {loading
          ? Array.from({ length: 12 }).map((_, i) => <StatsCardSkeleton key={i} />)
          : statsCards.map((card) => (
              <Card key={card.label} className="p-4 hover:shadow-md transition-shadow">
                <div className="flex items-center gap-3">
                  <div className={`flex items-center justify-center size-10 rounded-lg shrink-0 ${card.iconBg}`}>
                    <card.icon className="size-5" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs text-muted-foreground font-medium truncate">{card.label}</p>
                    <p className="text-lg font-bold truncate">{card.value}</p>
                    <div className="flex items-center gap-1 mt-0.5">
                      {card.trendUp ? (
                        <ArrowUpRight className="size-3 text-emerald-500" />
                      ) : (
                        <ArrowDownRight className="size-3 text-red-500" />
                      )}
                      <span
                        className={`text-xs font-medium ${
                          card.trendUp ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'
                        }`}
                      >
                        {card.trend}
                      </span>
                      <span className="text-xs text-muted-foreground ml-1 truncate">{card.sub}</span>
                    </div>
                  </div>
                </div>
              </Card>
            ))}
      </div>

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Revenue Chart */}
        {loading ? (
          <ChartSkeleton />
        ) : (
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-base">Revenue Overview</CardTitle>
                  <CardDescription>Monthly revenue for the last 6 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>
              <ChartContainer config={revenueChartConfig} className="h-[280px] w-full">
                <AreaChart data={revenueChartData} margin={{ top: 5, right: 10, left: 10, bottom: 0 }}>
                  <defs>
                    <linearGradient id="revenueGradient" 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>
                  </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}
                    tickFormatter={(v: number) => `৳${(v / 1000).toFixed(0)}k`}
                    className="text-xs"
                  />
                  <ChartTooltip content={<ChartTooltipContent />} />
                  <Area
                    type="monotone"
                    dataKey="revenue"
                    stroke="hsl(var(--chart-1))"
                    fill="url(#revenueGradient)"
                    strokeWidth={2}
                    dot={false}
                    activeDot={{ r: 4 }}
                  />
                </AreaChart>
              </ChartContainer>
            </CardContent>
          </Card>
        )}

        {/* User Growth Chart */}
        {loading ? (
          <ChartSkeleton />
        ) : (
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-base">User Growth</CardTitle>
                  <CardDescription>New user registrations by month</CardDescription>
                </div>
                <Badge variant="secondary" className="flex items-center gap-1">
                  <TrendingUp className="size-3 text-emerald-500" />
                  Growing
                </Badge>
              </div>
            </CardHeader>
            <CardContent>
              <ChartContainer config={growthChartConfig} className="h-[280px] w-full">
                <BarChart data={growthChartData} 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} className="text-xs" />
                  <ChartTooltip content={<ChartTooltipContent />} />
                  <Bar
                    dataKey="newUsers"
                    fill="hsl(var(--chart-3))"
                    radius={[4, 4, 0, 0]}
                    maxBarSize={40}
                  />
                  <Bar
                    dataKey="active"
                    fill="hsl(var(--chart-1))"
                    radius={[4, 4, 0, 0]}
                    maxBarSize={40}
                    fillOpacity={0.6}
                  />
                </BarChart>
              </ChartContainer>
            </CardContent>
          </Card>
        )}
      </div>

      {/* Recent Activity Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Invoices */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base">Recent Invoices</CardTitle>
                <CardDescription>Last 5 invoices created</CardDescription>
              </div>
              <Button variant="ghost" size="sm" onClick={() => setCurrentView('invoices')}>
                View All
                <ArrowUpRight className="size-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="space-y-3">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Skeleton key={i} className="h-12 w-full" />
                ))}
              </div>
            ) : stats?.recentInvoices && stats.recentInvoices.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Invoice</TableHead>
                    <TableHead>Client</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Date</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stats.recentInvoices.map((invoice) => (
                    <TableRow key={invoice.id} className="cursor-pointer">
                      <TableCell className="font-mono text-xs">{invoice.invoiceNumber}</TableCell>
                      <TableCell className="font-medium">{invoice.user.name}</TableCell>
                      <TableCell>{formatCurrency(invoice.totalAmount)}</TableCell>
                      <TableCell>
                        <Badge
                          variant="secondary"
                          className={invoiceStatusColor[invoice.status] || ''}
                        >
                          {invoice.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right text-muted-foreground text-xs">
                        {formatDate(invoice.createdAt)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                <FileText className="size-8 mx-auto mb-2 opacity-50" />
                <p className="text-sm">No invoices yet</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Tickets */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base">Recent Tickets</CardTitle>
                <CardDescription>Last 5 support tickets</CardDescription>
              </div>
              <Button variant="ghost" size="sm" onClick={() => setCurrentView('tickets')}>
                View All
                <ArrowUpRight className="size-4" />
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="space-y-3">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Skeleton key={i} className="h-12 w-full" />
                ))}
              </div>
            ) : recentTickets.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Subject</TableHead>
                    <TableHead>Client</TableHead>
                    <TableHead>Priority</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Date</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {recentTickets.map((ticket) => (
                    <TableRow key={ticket.id} className="cursor-pointer">
                      <TableCell className="font-medium max-w-[140px] truncate">
                        {ticket.subject}
                      </TableCell>
                      <TableCell className="text-muted-foreground text-xs">
                        {ticket.user.name}
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant="secondary"
                          className={ticketPriorityColor[ticket.priority] || ''}
                        >
                          {ticket.priority}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant="secondary"
                          className={ticketStatusColor[ticket.status] || ''}
                        >
                          {ticket.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right text-muted-foreground text-xs">
                        {formatDate(ticket.createdAt)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                <HelpCircle className="size-8 mx-auto mb-2 opacity-50" />
                <p className="text-sm">No tickets yet</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Quick Actions</CardTitle>
          <CardDescription>Common tasks and shortcuts</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            <Button
              className="h-auto py-4 flex-col gap-2"
              onClick={() => {
                setCurrentView('clients')
              }}
            >
              <Plus className="size-5" />
              <span>Add Client</span>
            </Button>
            <Button
              variant="outline"
              className="h-auto py-4 flex-col gap-2"
              onClick={() => setCurrentView('invoices')}
            >
              <FileText className="size-5" />
              <span>Generate Invoices</span>
            </Button>
            <Button
              variant="outline"
              className="h-auto py-4 flex-col gap-2"
              onClick={() => setCurrentView('reports')}
            >
              <BarChart3 className="size-5" />
              <span>View Reports</span>
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
