import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';

import type { AdminBillingDashboardProps } from '@/types/admin';

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    Head: ({ title }: { title: string }) => <title>{title}</title>,
    usePage: vi.fn(() => ({
      url: '/admin/billing',
      props: {
        auth: { user: { name: 'Admin', email: 'admin@test.com', is_admin: true } },
        features: {
          billing: true,
          socialAuth: false,
          emailVerification: true,
          apiTokens: true,
          userSettings: true,
          notifications: false,
          admin: true,
        },
      },
    })),
    Link: ({
      children,
      href,
      ...rest
    }: {
      children: React.ReactNode;
      href: string;
      className?: string;
    }) => (
      <a href={href} {...rest}>
        {children}
      </a>
    ),
    router: {
      patch: vi.fn(),
      delete: vi.fn(),
      post: vi.fn(),
      get: vi.fn(),
      on: vi.fn(() => vi.fn()),
    },
  };
});

vi.mock('@/Components/theme/use-theme', () => ({
  useTheme: vi.fn(() => ({ theme: 'system', setTheme: vi.fn(), resolvedTheme: 'light' })),
}));

vi.mock('@/Components/ui/count-up', () => ({
  CountUp: ({ end, format }: { end: number; format?: (n: number) => string }) => (
    <span>{format ? format(end) : end}</span>
  ),
}));

vi.mock('@/lib/analytics', () => ({
  trackProductEvent: vi.fn(),
}));

// Recharts mocks — prevent canvas-related errors in jsdom
vi.mock('recharts', () => ({
  ResponsiveContainer: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  AreaChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="area-chart">{children}</div>
  ),
  BarChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="bar-chart">{children}</div>
  ),
  PieChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="pie-chart">{children}</div>
  ),
  Pie: () => null,
  Cell: () => null,
  Area: () => null,
  Bar: () => null,
  LabelList: () => null,
  XAxis: () => null,
  YAxis: () => null,
  CartesianGrid: () => null,
  Tooltip: () => null,
  Legend: () => null,
}));

import BillingDashboard from './Dashboard';

const defaultProps: AdminBillingDashboardProps = {
  stats: {
    active_subscriptions: 42,
    trialing: 8,
    past_due: 3,
    canceled: 5,
    total_ever: 60,
    mrr: 1260,
    churn_rate: 2.5,
    trial_conversion_rate: 35,
    ltv: 180,
  },
  tier_distribution: [
    { tier: 'pro', count: 30 },
    { tier: 'team', count: 12 },
  ],
  status_breakdown: [
    { status: 'active', count: 42 },
    { status: 'canceled', count: 5 },
  ],
  growth_chart: [
    { date: '2025-01-01', count: 5 },
    { date: '2025-01-02', count: 8 },
  ],
  trial_stats: {
    active_trials: 8,
    expiring_soon: 2,
  },
  tier_usage: [
    {
      tier: 'pro',
      user_count: 30,
      avg_sites: 2.1,
      avg_analyses_30d: 4.5,
      avg_drafts_30d: 3.2,
      avg_applied_recommendations_30d: 1.8,
      pct_gsc_connected: 85,
      pct_wp_connected: 70,
    },
  ],
  churn_breakdown: {
    voluntary: 3,
    involuntary: 1,
    unknown: 1,
  },
  checkout_funnel: {
    checkout_started: 50,
    checkout_completed: 35,
    checkout_abandoned: 15,
    conversion_rate: 70,
  },
  ltv_by_tier: {
    pro: { tier: 'pro', arpu: 29, ltv: 180 },
  },
  recent_events: [
    {
      id: 1,
      event: 'billing.subscription_created',
      user_id: 10,
      user_name: 'Alice',
      metadata: { tier: 'pro' },
      created_at: new Date().toISOString(),
    },
  ],
};

describe('BillingDashboard', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders the Billing heading', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByRole('heading', { name: /Billing/i, level: 1 })).toBeInTheDocument();
  });

  it('renders active subscriptions stat', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByText('Active Subscriptions')).toBeInTheDocument();
    expect(screen.getByText('42')).toBeInTheDocument();
  });

  it('renders MRR stat', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByText('MRR')).toBeInTheDocument();
  });

  it('renders churn rate stat', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByText('Churn Rate (30d)')).toBeInTheDocument();
  });

  it('renders trial stats', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByText('Trialing')).toBeInTheDocument();
    expect(screen.getByText('8')).toBeInTheDocument();
  });

  it('renders recent billing events', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByText('billing.subscription_created')).toBeInTheDocument();
    expect(screen.getByText('Alice')).toBeInTheDocument();
  });

  it('shows empty state when no recent events', () => {
    render(<BillingDashboard {...defaultProps} recent_events={[]} />);
    expect(screen.getByText('No billing events')).toBeInTheDocument();
  });

  it('renders past due stat', () => {
    render(<BillingDashboard {...defaultProps} />);
    expect(screen.getByText('Past Due')).toBeInTheDocument();
  });
});
