import { Activity, CreditCard, DollarSign, TrendingDown, TrendingUp, Users } from 'lucide-react';

import { Suspense, lazy, useEffect } from 'react';

import { Head, Link } from '@inertiajs/react';

import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
import { TierUsageTable } from '@/Components/admin/TierUsageTable';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/Components/ui/card';
import { CountUp } from '@/Components/ui/count-up';
import { EmptyState } from '@/Components/ui/empty-state';
import { Skeleton } from '@/Components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import AdminLayout from '@/Layouts/AdminLayout';
import { trackProductEvent } from '@/lib/analytics';
import { ADMIN_BILLING_DASHBOARD_VIEWED } from '@/lib/event-catalog';
import { formatCurrency, formatRelativeTime } from '@/lib/format';
import type { AdminBillingDashboardProps, LtvByTierEntry } from '@/types/admin';

// Pie chart skeleton: circle + legend rows
const PieChartSkeleton = () => (
  <div className="flex h-[250px] items-center justify-center gap-8">
    <Skeleton className="h-40 w-40 rounded-full" />
    <div className="space-y-2">
      {Array.from({ length: 4 }).map((_, i) => (
        <div key={i} className="flex items-center gap-2">
          <Skeleton className="h-3 w-3 rounded-sm" />
          <Skeleton className="h-3 w-16" />
        </div>
      ))}
    </div>
  </div>
);

// Bar chart skeleton: vertical bars + axes
const BarChartSkeleton = () => (
  <div className="h-[250px] w-full p-2">
    <div className="flex h-full items-end gap-3 px-8 pb-8">
      {[60, 35, 80, 20, 50].map((h, i) => (
        <Skeleton key={i} className="flex-1 rounded-t" style={{ height: `${h}%` }} />
      ))}
    </div>
    <div className="flex justify-between px-8">
      {Array.from({ length: 5 }).map((_, i) => (
        <Skeleton key={i} className="h-3 w-12" />
      ))}
    </div>
  </div>
);

// Area chart skeleton for growth chart
const AreaChartSkeleton = () => (
  <div className="h-[300px] w-full space-y-3 p-2">
    <div className="flex h-full gap-2">
      <div className="flex flex-col justify-between py-2">
        {Array.from({ length: 5 }).map((_, i) => (
          <Skeleton key={i} className="h-3 w-6" />
        ))}
      </div>
      <div className="flex-1 flex flex-col justify-end gap-0.5">
        <Skeleton className="w-full rounded-t-lg" style={{ height: '40%' }} />
      </div>
    </div>
    <div className="flex justify-between px-8">
      {Array.from({ length: 6 }).map((_, i) => (
        <Skeleton key={i} className="h-3 w-10" />
      ))}
    </div>
  </div>
);

// Lazy load tier distribution pie chart
const LazyTierChart = lazy(async () => {
  const { PieChart, Pie, Cell, ChartContainer, ChartTooltip, Legend, CHART_COLORS } =
    await import('@/Components/ui/chart');
  return {
    default: ({ data }: { data: { tier: string; count: number }[] }) => (
      <ChartContainer height={250}>
        <PieChart>
          <Pie
            data={data}
            dataKey="count"
            nameKey="tier"
            cx="50%"
            cy="50%"
            outerRadius={80}
            label={({ name, value }) => `${name}: ${value}`}
            animationDuration={800}
            animationBegin={100}
          >
            {data.map((_entry, index) => (
              <Cell key={`cell-${index}`} fill={CHART_COLORS[index % CHART_COLORS.length]} />
            ))}
          </Pie>
          <ChartTooltip />
          <Legend />
        </PieChart>
      </ChartContainer>
    ),
  };
});

// Lazy load status breakdown bar chart
const LazyStatusChart = lazy(async () => {
  const {
    BarChart,
    Bar,
    CartesianGrid,
    Cell,
    ChartContainer,
    ChartTooltip,
    XAxis,
    YAxis,
    CHART_COLORS,
  } = await import('@/Components/ui/chart');
  const { SUBSCRIPTION_STATUS_COLORS } = await import('@/config/billing-constants');
  return {
    default: ({ data }: { data: { status: string; count: number }[] }) => (
      <ChartContainer height={250}>
        <BarChart data={data}>
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis dataKey="status" className="text-xs" />
          <YAxis allowDecimals={false} className="text-xs" />
          <ChartTooltip />
          <Bar dataKey="count" name="Subscriptions" radius={[4, 4, 0, 0]} animationDuration={600}>
            {data.map((entry, index) => (
              <Cell
                key={`cell-${index}`}
                fill={
                  SUBSCRIPTION_STATUS_COLORS[entry.status] ??
                  CHART_COLORS[index % CHART_COLORS.length]
                }
              />
            ))}
          </Bar>
        </BarChart>
      </ChartContainer>
    ),
  };
});

// Lazy load growth area chart
const LazyGrowthChart = lazy(async () => {
  const { AreaChart, Area, CartesianGrid, ChartContainer, ChartTooltip, XAxis, YAxis } =
    await import('@/Components/ui/chart');
  return {
    default: ({ data }: { data: { date: string; count: number }[] }) => (
      <ChartContainer height={300}>
        <AreaChart data={data}>
          <defs>
            <linearGradient id="billingGrowthGradient" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.3} />
              <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0} />
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis
            dataKey="date"
            tickFormatter={(v) =>
              new Date(v).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
            }
            className="text-xs"
          />
          <YAxis allowDecimals={false} className="text-xs" />
          <ChartTooltip />
          <Area
            type="monotone"
            dataKey="count"
            name="Subscriptions"
            stroke="hsl(var(--primary))"
            fill="url(#billingGrowthGradient)"
            strokeWidth={2}
            animationDuration={800}
            animationBegin={200}
          />
        </AreaChart>
      </ChartContainer>
    ),
  };
});

export default function BillingDashboard({
  stats,
  tier_distribution,
  status_breakdown,
  growth_chart,
  trial_stats,
  tier_usage,
  churn_breakdown,
  checkout_funnel,
  ltv_by_tier,
  recent_events,
}: AdminBillingDashboardProps) {
  useEffect(() => {
    trackProductEvent(ADMIN_BILLING_DASHBOARD_VIEWED, {
      active_subscriptions: stats.active_subscriptions,
      mrr: stats.mrr,
    });
    // intentional: fire-once on mount
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const hasSubscriptions = stats.total_ever > 0;

  const primaryKpis: StatCard[] = [
    {
      title: 'MRR',
      value: stats.mrr,
      icon: DollarSign,
      format: formatCurrency,
      description: 'Monthly recurring revenue',
    },
    {
      title: 'LTV (est.)',
      value: stats.ltv,
      icon: DollarSign,
      format: (n) => (n > 0 ? formatCurrency(n) : '—'),
      description: 'ARPU ÷ monthly churn',
    },
    {
      title: 'Active Subscriptions',
      value: stats.active_subscriptions,
      icon: CreditCard,
      description: 'Paying customers',
      href: '/admin/billing/subscriptions?status=active',
    },
    {
      title: 'Churn Rate (30d)',
      value: stats.churn_rate,
      icon: TrendingDown,
      format: (n) => `${n}%`,
      description: 'Cancellations vs active',
    },
    {
      title: 'Trial Conversion',
      value: stats.trial_conversion_rate,
      icon: TrendingUp,
      format: (n) => `${n}%`,
      description: 'Trial to paid',
      href: '/admin/billing/subscriptions?status=trialing',
    },
  ];

  return (
    <AdminLayout>
      <Head title="Admin - Billing" />
      <PageHeader
        title="Billing Overview"
        description="Revenue metrics and subscription analytics"
        actions={
          <Button variant="outline" size="sm" asChild>
            <Link href="/admin/billing/subscriptions">View All Subscriptions</Link>
          </Button>
        }
      />

      <div className="container py-6 space-y-6">
        {/* Primary KPIs */}
        <AdminStatsGrid stats={primaryKpis} />

        {/* Secondary stats */}
        <div className="grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Trialing</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-xl font-bold">
                <CountUp end={stats.trialing} />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Past Due</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-xl font-bold text-warning">
                <CountUp end={stats.past_due} />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Canceled</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-xl font-bold">
                <CountUp end={stats.canceled} />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium">Trials Expiring Soon</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-xl font-bold text-warning">
                <CountUp end={trial_stats.expiring_soon} />
              </div>
              <p className="text-xs text-muted-foreground">Within 3 days</p>
            </CardContent>
          </Card>
        </div>

        {/* DUNNING-002: Churn type breakdown */}
        {(churn_breakdown.voluntary > 0 ||
          churn_breakdown.involuntary > 0 ||
          churn_breakdown.unknown > 0) && (
          <div className="grid gap-4 grid-cols-1 md:grid-cols-3">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">Voluntary Churn (30d)</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold">
                  <CountUp end={churn_breakdown.voluntary} />
                </div>
                <p className="text-xs text-muted-foreground">User-initiated cancellations</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">Involuntary Churn (30d)</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold text-destructive">
                  <CountUp end={churn_breakdown.involuntary} />
                </div>
                <p className="text-xs text-muted-foreground">Payment failure cancellations</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm font-medium">Unknown Churn (30d)</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-xl font-bold text-muted-foreground">
                  <CountUp end={churn_breakdown.unknown} />
                </div>
                <p className="text-xs text-muted-foreground">Pre-tracking cancellations</p>
              </CardContent>
            </Card>
          </div>
        )}

        {/* CHECKOUT-002: Checkout funnel */}
        {checkout_funnel.checkout_started > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Checkout Funnel (30d)</CardTitle>
              <CardDescription>
                Conversion: {checkout_funnel.conversion_rate}% of started checkouts completed
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
                <div className="text-center">
                  <div className="text-2xl font-bold">
                    <CountUp end={checkout_funnel.checkout_started} />
                  </div>
                  <p className="text-sm text-muted-foreground">Started</p>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-success">
                    <CountUp end={checkout_funnel.checkout_completed} />
                  </div>
                  <p className="text-sm text-muted-foreground">Completed</p>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-warning">
                    <CountUp end={checkout_funnel.checkout_abandoned} />
                  </div>
                  <p className="text-sm text-muted-foreground">Abandoned</p>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* SP-D10-002: LTV by Tier */}
        {Object.keys(ltv_by_tier).length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>LTV by Tier</CardTitle>
              <CardDescription>
                Estimated lifetime value per tier — ARPU ÷ monthly churn rate
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Tier</TableHead>
                      <TableHead className="text-right">ARPU / mo</TableHead>
                      <TableHead className="text-right">Est. LTV</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {(Object.values(ltv_by_tier) as LtvByTierEntry[]).map((row) => (
                      <TableRow key={row.tier} className="hover:bg-muted/50">
                        <TableCell className="font-medium capitalize">{row.tier}</TableCell>
                        <TableCell className="text-right tabular-nums">
                          {formatCurrency(row.arpu)}
                        </TableCell>
                        <TableCell className="text-right tabular-nums font-semibold">
                          {formatCurrency(row.ltv)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        )}

        {!hasSubscriptions ? (
          <EmptyState
            icon={CreditCard}
            title="No subscriptions yet"
            description="Subscription data will appear here once users start subscribing."
          />
        ) : (
          <>
            {/* Charts row */}
            <div className="grid gap-6 md:grid-cols-2">
              {/* Tier Distribution */}
              <Card>
                <CardHeader>
                  <CardTitle>Subscription by Tier</CardTitle>
                  <CardDescription>Active subscription distribution</CardDescription>
                </CardHeader>
                <CardContent>
                  {tier_distribution.length === 0 ? (
                    <EmptyState
                      icon={Users}
                      title="No active subscriptions"
                      description="Tier data will appear when subscriptions are active."
                      size="sm"
                    />
                  ) : (
                    <ChartErrorBoundary>
                      <Suspense fallback={<PieChartSkeleton />}>
                        <LazyTierChart data={tier_distribution} />
                      </Suspense>
                    </ChartErrorBoundary>
                  )}
                </CardContent>
              </Card>

              {/* Status Breakdown */}
              <Card>
                <CardHeader>
                  <CardTitle>Status Breakdown</CardTitle>
                  <CardDescription>All subscriptions by status</CardDescription>
                </CardHeader>
                <CardContent>
                  {status_breakdown.length === 0 ? (
                    <EmptyState
                      icon={Activity}
                      title="No data"
                      description="Status breakdown will appear here."
                      size="sm"
                    />
                  ) : (
                    <ChartErrorBoundary>
                      <Suspense fallback={<BarChartSkeleton />}>
                        <LazyStatusChart data={status_breakdown} />
                      </Suspense>
                    </ChartErrorBoundary>
                  )}
                </CardContent>
              </Card>
            </div>

            {/* Growth Chart */}
            <Card>
              <CardHeader>
                <CardTitle>New Subscriptions</CardTitle>
                <CardDescription>New subscriptions over the last 30 days</CardDescription>
              </CardHeader>
              <CardContent>
                {growth_chart.length === 0 ? (
                  <EmptyState
                    icon={TrendingUp}
                    title="No recent subscriptions"
                    description="Subscription growth data will appear here."
                    size="sm"
                  />
                ) : (
                  <ChartErrorBoundary>
                    <Suspense fallback={<AreaChartSkeleton />}>
                      <LazyGrowthChart data={growth_chart} />
                    </Suspense>
                  </ChartErrorBoundary>
                )}
              </CardContent>
            </Card>
          </>
        )}

        {/* Usage by Tier */}
        <TierUsageTable data={tier_usage} />

        {/* Recent Billing Events */}
        <Card>
          <CardHeader>
            <CardTitle>Recent Billing Events</CardTitle>
            <CardDescription>Latest billing-related audit log entries</CardDescription>
          </CardHeader>
          <CardContent>
            {recent_events.length === 0 ? (
              <EmptyState
                icon={Activity}
                title="No billing events yet"
                description="Billing events will appear here as subscription changes occur."
                size="sm"
              />
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Event</TableHead>
                      <TableHead>User</TableHead>
                      <TableHead>Time</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {recent_events.map((event) => (
                      <TableRow key={event.id} className="hover:bg-muted/50">
                        <TableCell>
                          <Link
                            href={`/admin/audit-logs/${event.id}`}
                            className="hover:opacity-80 transition-opacity"
                          >
                            <Badge variant="secondary">{event.event}</Badge>
                          </Link>
                        </TableCell>
                        <TableCell className="text-sm">
                          {event.user_id ? (
                            <Link
                              href={`/admin/users/${event.user_id}`}
                              className="hover:underline"
                            >
                              {event.user_name ?? `User #${event.user_id}`}
                            </Link>
                          ) : (
                            <span className="text-muted-foreground">System</span>
                          )}
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {formatRelativeTime(event.created_at)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </AdminLayout>
  );
}
