import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { Route, Routes } from 'react-router-dom';
import { renderWithProviders } from '../test/utils';

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

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

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

const PAYLOAD = {
  patient: { uuid: 'abc', name: 'دنیا خلیلی', national_code: '1744023654' },
  data: [
    { uuid: 'i1', number: 12345, issued_at: 1717000000, total_rials: 2350000, status: 'paid',
      service_title: 'روکش دندان',
      items: [{ uuid: 'it1', title: 'روکش دندان', quantity: 1, total_rials: 2350000, patient_rials: 2350000 }] },
    { uuid: 'i2', number: 52614, issued_at: 1718000000, total_rials: 6000000, status: 'unsettled',
      service_title: 'طرح لبخند', items: [] },
  ],
  meta: { totalRecords: 2, totalPages: 1, currentPage: 1 },
};

function renderPage() {
  return renderWithProviders(
    <Routes>
      <Route path="/admin/my-payments/:patientUuid" element={<MyPaymentDetailPage />} />
    </Routes>,
    { route: '/admin/my-payments/abc' },
  );
}

beforeEach(() => {
  get.mockReset();
  get.mockResolvedValue({ success: true, data: PAYLOAD });
});

describe('MyPaymentDetailPage (پرداخت‌های ثبت‌شده)', () => {
  it('renders the patient header and invoice rows', async () => {
    renderPage();
    expect(await screen.findByText('دنیا خلیلی')).toBeInTheDocument();
    expect(screen.getByText(/1744023654/)).toBeInTheDocument();
    expect(screen.getByText('روکش دندان')).toBeInTheDocument();
    expect(screen.getByText('طرح لبخند')).toBeInTheDocument();
    expect(screen.getByText('پرداخت شده')).toBeInTheDocument();
    expect(screen.getByText('تسویه نشده')).toBeInTheDocument();
  });

  it('fetches invoices for the patient uuid from the route', async () => {
    renderPage();
    await screen.findByText('دنیا خلیلی');
    expect(get.mock.calls[0][0]).toContain('/api/v1/my/billing/patients/abc/invoices');
  });

  it('expands a row to show its line items on بیشتر', async () => {
    renderPage();
    await screen.findByText('روکش دندان');
    fireEvent.click(screen.getAllByRole('button', { name: /بیشتر/ })[0]);
    // the item breakdown appears (title repeated inside the expanded sub-row)
    expect(await screen.findAllByText('روکش دندان')).toHaveLength(2);
  });

  it('shows an empty state when the patient has no invoices', async () => {
    get.mockResolvedValue({ success: true, data: { patient: PAYLOAD.patient, data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } } });
    renderPage();
    expect(await screen.findByText('صورتحسابی ثبت نشده است')).toBeInTheDocument();
  });
});
