import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import ShoppingListPricesPage from '../../../../../src/app/(dashboard)/shopping-lists/prices/page';
import * as useApiModule from '@/lib/useApi';
import * as PricesService from '@/services/prices';

vi.mock('@/lib/useApi');
vi.mock('@/services/prices');
const { mockPush } = vi.hoisted(() => ({
  mockPush: vi.fn(),
}));

vi.mock('next/navigation', () => ({
  useRouter: () => ({
    push: mockPush,
    back: vi.fn(),
  }),
}));

describe('ShoppingListPricesPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(useApiModule.useApi).mockReturnValue({
      householdId: 'hh1',
      isLoading: false,
      user: null,
      token: '123',
    } as any);

    vi.mocked(PricesService.getPriceAnalytics).mockResolvedValue({
      timeframe: { start: '2026-04-01', end: '2026-05-14' },
      totalSpent: 150.00,
      totalRecords: 10,
      storeBreakdown: [
        { storeId: 'store1', storeName: 'Costco', spent: 100 },
        { storeId: 'store2', storeName: 'Trader Joes', spent: 50 },
      ],
      recentPriceChanges: [
        {
          productId: 'p1',
          productName: 'Milk',
          storeId: 'store1',
          storeName: 'Costco',
          oldPrice: 3.50,
          newPrice: 4.00,
          percentageChange: 14.28,
          trend: 'up',
        }
      ],
      priceAlerts: [
        { productName: 'Bread', storeName: 'Costco', changePercent: 15, previousPrice: 2.00, currentPrice: 2.30 }
      ],
      spendingOverTime: [
        { period: 'Apr', total: 50 },
        { period: 'May', total: 100 }
      ],
      spendingByCategory: [
        { category: 'Produce', total: 30 },
        { category: 'Bakery', total: 20 }
      ],
      averageBasketByStore: [
        { storeId: 'store1', storeName: 'Costco', avgTotal: 150.00, tripCount: 5 },
        { storeId: 'store2', storeName: 'Trader Joes', avgTotal: 50.00, tripCount: 2 },
      ],
    } as any);
  });

  it('renders loading initially', () => {
    vi.mocked(useApiModule.useApi).mockReturnValue({ householdId: null, isLoading: true } as any);
    render(<ShoppingListPricesPage />);
    expect(screen.getByText(/Synthesizing financial graphs/i)).toBeInTheDocument();
  });

  it('loads and displays analytics', async () => {
    render(<ShoppingListPricesPage />);
    await waitFor(() => {
      expect(screen.getByText('$150.00')).toBeInTheDocument();
      expect(screen.getByText('Costco')).toBeInTheDocument();
      expect(screen.getByText('Trader Joes')).toBeInTheDocument();
    });
  });

  it('handles fetch errors gracefully', async () => {
    vi.mocked(PricesService.getPriceAnalytics).mockRejectedValue(new Error('Analytics failed'));
    render(<ShoppingListPricesPage />);
    
    await waitFor(() => {
      expect(screen.getByText(/Analytics failed/i)).toBeInTheDocument();
    });
  });

  it('navigates back to checklists when button is clicked', async () => {
    render(<ShoppingListPricesPage />);
    await screen.findByText('Costco');

    const backBtn = screen.getByRole('button', { name: /Back to Checklists/i });
    fireEvent.click(backBtn);

    expect(mockPush).toHaveBeenCalledWith('/shopping-lists');
  });
});
