'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  DollarSign,
  AlertTriangle,
  CheckCircle2,
  Clock,
  FileText,
  Send,
  TrendingUp,
  Loader2,
  ArrowUpRight,
  ArrowDownRight,
  RefreshCcw,
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
  type ChartConfig,
} from '@/components/ui/chart'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/hooks/use-toast'
import { api } from '@/lib/api'
import { Bar, BarChart, XAxis, YAxis } from 'recharts'

interface Invoice {
  id: string
  invoiceNumber: string
  amount: number
  tax: number
  discount: number
  lateFee: number
  totalAmount: number
  paidAmount: number
  status: string
  dueDate: string
  createdAt: string
  user: { id: string; name: string; email: string }
}

interface DashboardStats {
  users: { total: number; active: number; expired: number; suspended: number; pending: number }
  subscriptions: { total: number; active: 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 }
  network: { onlineOLTs: number; onus: Record<string, number>; totalONUs: number }
  plans: { active: number }
  areas: { total: number }
  resellers: { total: number }
  recentInvoices: Invoice[]
}

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

const chartConfig: ChartConfig = {
  revenue: {
    label: 'Revenue Collected',
    color: 'var(--chart-1, #10b981)',
  },
  billed: {
    label: 'Total Billed',
    color: 'var(--chart-2, #f59e0b)',
  },
}

const statusColors: Record<string, string> = {
  PAID: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-400',
  UNPAID: 'bg-gray-100 text-gray-800 dark:bg-gray-800/40 dark:text-gray-400',
  DUE: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-400',
  PARTIAL: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-400',
}

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

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

export default function BillingView() {
  const { toast } = useToast()
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [recentInvoices, setRecentInvoices] = useState<Invoice[]>([])
  const [revenueData, setRevenueData] = useState<RevenueData[]>([])
  const [loading, setLoading] = useState(true)
  const [generating, setGenerating] = useState(false)

  const fetchData = useCallback(async () => {
    try {
      setLoading(true)
      const [statsRes, invoicesRes, revenueRes] = await Promise.all([
        api.get<{ success: boolean; data: DashboardStats }>('/api/dashboard/stats'),
        api.get<{ success: boolean; data: { invoices: Invoice[] } }>('/api/invoices?limit=10'),
        api.get<{ success: boolean; data: { data: RevenueData[] } }>(
          '/api/dashboard/revenue?period=monthly&months=6'
        ),
      ])

      if (statsRes.success) setStats(statsRes.data)
      if (invoicesRes.success) setRecentInvoices(invoicesRes.data.invoices)
      if (revenueRes.success) setRevenueData(revenueRes.data.data)
    } catch {
      toast({ title: 'Error', description: 'Failed to load billing data', variant: 'destructive' })
    } finally {
      setLoading(false)
    }
  }, [toast])

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

  const handleGenerateInvoices = async () => {
    try {
      setGenerating(true)
      const res = await api.post<{ success: boolean; message: string }>('/api/invoices/generate')
      if (res.success) {
        toast({ title: 'Success', description: res.message })
        fetchData()
      }
    } catch {
      toast({ title: 'Error', description: 'Failed to generate invoices', variant: 'destructive' })
    } finally {
      setGenerating(false)
    }
  }

  const handleSendReminders = async () => {
    try {
      toast({ title: 'Info', description: 'Sending reminders to all clients with due invoices...' })
      // In production, this would call a reminder API
    } catch {
      toast({ title: 'Error', description: 'Failed to send reminders', variant: 'destructive' })
    }
  }

  const chartData = revenueData.map((item) => ({
    month: `${item.month} ${item.year}`,
    revenue: item.revenue,
    billed: item.invoices * 100, // Estimated billed
  }))

  const pendingCount =
    stats?.invoices.breakdown.UNPAID?.count || 0 +
    stats?.invoices.breakdown.DUE?.count || 0 +
    stats?.invoices.breakdown.PARTIAL?.count || 0

  if (loading) {
    return (
      <div className="space-y-6 p-4 md:p-6">
        <div className="flex items-center justify-between">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-9 w-40" />
        </div>
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[...Array(4)].map((_, i) => (
            <Skeleton key={i} className="h-32" />
          ))}
        </div>
        <Skeleton className="h-96" />
      </div>
    )
  }

  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">Billing</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Overview of revenue, invoices, and billing operations
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={fetchData}>
            <RefreshCcw className="size-4" />
            <span className="hidden sm:inline">Refresh</span>
          </Button>
          <Button
            size="sm"
            onClick={handleGenerateInvoices}
            disabled={generating}
          >
            {generating ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              <FileText className="size-4" />
            )}
            Generate Monthly Invoices
          </Button>
        </div>
      </div>

      {/* Overview Cards */}
      <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 Revenue
            </CardTitle>
            <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-2">
              <DollarSign className="size-4 text-emerald-600 dark:text-emerald-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatCurrency(stats?.revenue.total || 0)}
            </div>
            <div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
              <ArrowUpRight className="size-3 text-emerald-500" />
              <span>This month: {formatCurrency(stats?.revenue.thisMonth || 0)}</span>
            </div>
          </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 Due
            </CardTitle>
            <div className="bg-amber-100 dark:bg-amber-900/30 rounded-full p-2">
              <AlertTriangle className="size-4 text-amber-600 dark:text-amber-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatCurrency(stats?.revenue.unpaid || 0)}
            </div>
            <div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
              <ArrowDownRight className="size-3 text-amber-500" />
              <span>{stats?.invoices.dueOverdue || 0} overdue invoices</span>
            </div>
          </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">
              Paid This Month
            </CardTitle>
            <div className="bg-sky-100 dark:bg-sky-900/30 rounded-full p-2">
              <CheckCircle2 className="size-4 text-sky-600 dark:text-sky-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {formatCurrency(stats?.revenue.thisMonth || 0)}
            </div>
            <div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
              <span>{stats?.revenue.thisMonthTransactions || 0} transactions</span>
            </div>
          </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 Invoices
            </CardTitle>
            <div className="bg-orange-100 dark:bg-orange-900/30 rounded-full p-2">
              <Clock className="size-4 text-orange-600 dark:text-orange-400" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{pendingCount}</div>
            <div className="flex items-center gap-1 mt-1 text-xs text-muted-foreground">
              <span>Requires attention</span>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Revenue Chart */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="size-5" />
            Monthly Revenue Comparison
          </CardTitle>
          <CardDescription>Paid revenue vs estimated billing over last 6 months</CardDescription>
        </CardHeader>
        <CardContent>
          <ChartContainer config={chartConfig} className="h-[300px] w-full">
            <BarChart data={chartData} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
              <XAxis
                dataKey="month"
                tickLine={false}
                axisLine={false}
                tickMargin={8}
              />
              <YAxis
                tickLine={false}
                axisLine={false}
                tickFormatter={(value) => `৳${(value / 1000).toFixed(0)}k`}
              />
              <ChartTooltip content={<ChartTooltipContent />} />
              <ChartLegend content={<ChartLegendContent />} />
              <Bar
                dataKey="revenue"
                fill="var(--color-revenue)"
                radius={[4, 4, 0, 0]}
              />
              <Bar
                dataKey="billed"
                fill="var(--color-billed)"
                radius={[4, 4, 0, 0]}
              />
            </BarChart>
          </ChartContainer>
        </CardContent>
      </Card>

      {/* Quick Actions + Recent Invoices */}
      <div className="grid gap-6 lg:grid-cols-3">
        {/* Quick Actions */}
        <Card>
          <CardHeader>
            <CardTitle>Quick Actions</CardTitle>
            <CardDescription>Common billing operations</CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            <Button
              className="w-full justify-start gap-3"
              variant="outline"
              onClick={handleGenerateInvoices}
              disabled={generating}
            >
              <div className="bg-emerald-100 dark:bg-emerald-900/30 rounded-full p-1.5">
                <FileText className="size-4 text-emerald-600 dark:text-emerald-400" />
              </div>
              <div className="text-left">
                <div className="text-sm font-medium">Generate Monthly Invoices</div>
                <div className="text-xs text-muted-foreground">
                  Auto-create invoices for active subscriptions
                </div>
              </div>
            </Button>
            <Button
              className="w-full justify-start gap-3"
              variant="outline"
              onClick={handleSendReminders}
            >
              <div className="bg-sky-100 dark:bg-sky-900/30 rounded-full p-1.5">
                <Send className="size-4 text-sky-600 dark:text-sky-400" />
              </div>
              <div className="text-left">
                <div className="text-sm font-medium">Send Reminders</div>
                <div className="text-xs text-muted-foreground">
                  Notify clients about due payments
                </div>
              </div>
            </Button>
            <Button className="w-full justify-start gap-3" variant="outline">
              <div className="bg-purple-100 dark:bg-purple-900/30 rounded-full p-1.5">
                <DollarSign className="size-4 text-purple-600 dark:text-purple-400" />
              </div>
              <div className="text-left">
                <div className="text-sm font-medium">Record Payment</div>
                <div className="text-xs text-muted-foreground">
                  Manually add a payment transaction
                </div>
              </div>
            </Button>
          </CardContent>
        </Card>

        {/* Recent Invoices */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>Recent Invoices</CardTitle>
            <CardDescription>Latest invoices generated in the system</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="max-h-96 overflow-y-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Invoice #</TableHead>
                    <TableHead>Client</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                    <TableHead>Due Date</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {recentInvoices.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                        No invoices found
                      </TableCell>
                    </TableRow>
                  ) : (
                    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 || 'Unknown'}
                        </TableCell>
                        <TableCell className="text-right font-medium">
                          {formatCurrency(invoice.totalAmount)}
                        </TableCell>
                        <TableCell>{formatDate(invoice.dueDate)}</TableCell>
                        <TableCell>
                          <Badge
                            variant="secondary"
                            className={statusColors[invoice.status] || ''}
                          >
                            {invoice.status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
