import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, within } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
import { formatRial } from '../lib/utils';

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({
  api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
  ApiError: class extends Error {},
}));

import { api } from '../lib/api';
import SubscriptionPage from './SubscriptionPage';

const get = api.get as ReturnType<typeof vi.fn>;

const PLANS = [
  { uuid: 'p-free', name: 'free', level: 0, max_secretaries: 1,
    features: { patient_records: false, services: false, sms_panel: false }, active: true, periods: [] },
  { uuid: 'p-basic', name: 'basic', level: 1, max_secretaries: 3,
    features: { patient_records: true, services: true, sms_panel: false }, active: true,
    periods: [
      { uuid: 'per-1m', label: 'یک ماهه', duration_months: 1, price_rials: 1000000, is_trial: false },
      { uuid: 'per-12m', label: 'یک ساله', duration_months: 12, price_rials: 9000000, is_trial: false },
    ] },
  { uuid: 'p-pro', name: 'professional', level: 2, max_secretaries: 10,
    features: { patient_records: true, services: true, sms_panel: true }, active: true, periods: [] },
];

function mockApi(overrides: Partial<Record<string, any>> = {}) {
  get.mockImplementation((url: string) => {
    if (url.includes('/subscription/plans')) return Promise.resolve({ success: true, data: PLANS });
    if (url.includes('/subscription/my')) return Promise.resolve({ success: true, data: overrides.my ?? {
      subscription: { plan: { name: 'basic', level: 1, max_secretaries: 3, features: {} }, is_trial: false, days_remaining: 25 },
      used_trial: true, effective_plan: null,
    } });
    if (url.includes('/payment/config')) return Promise.resolve({ success: true, data: { test_mode: true, appointment_fee_rials: 0, gateways: [] } });
    return Promise.resolve({ success: true, data: null });
  });
}

beforeEach(() => { get.mockReset(); mockApi(); });

describe('SubscriptionPage', () => {
  it('renders the three plans with the most-popular badge on the basic plan', async () => {
    renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
    expect(await screen.findByText('پلن پایه')).toBeInTheDocument();
    expect(screen.getByText('پلن رایگان')).toBeInTheDocument();
    expect(screen.getByText('پلن حرفه‌ای')).toBeInTheDocument();
    expect(screen.getByText('محبوب‌ترین')).toBeInTheDocument();
  });

  it('shows the current-plan banner with days remaining', async () => {
    renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
    expect(await screen.findByText(/پلن فعلی شما/)).toBeInTheDocument();
    expect(screen.getByText(/روز تا پایان اشتراک/)).toBeInTheDocument();
  });

  it('the period toggle switches the displayed price', async () => {
    renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
    const basicCard = (await screen.findByText('پلن پایه')).closest('div')!.parentElement!.parentElement!;
    const card = within(basicCard);
    // default = longest period (یک ساله)
    expect(card.getByText(formatRial(9000000))).toBeInTheDocument();
    // switch to monthly
    fireEvent.click(card.getByRole('tab', { name: 'یک ماهه' }));
    expect(card.getByText(formatRial(1000000))).toBeInTheDocument();
  });

  it('clicking the buy button opens the payment modal with the selected amount', async () => {
    renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
    // basic is the current plan → button reads "تمدید اشتراک"
    fireEvent.click(await screen.findByText('تمدید اشتراک'));
    expect(await screen.findByText('پرداخت اشتراک')).toBeInTheDocument();
    expect(screen.getByText('درگاه آزمایشی فعال است')).toBeInTheDocument();
  });
});
