import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, waitFor } from '@testing-library/react';
import { Routes, Route } from 'react-router-dom';
import { renderWithProviders } from '../test/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 PatientDetailPage from './PatientDetailPage';

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

beforeEach(() => {
  get.mockReset();
  get.mockImplementation((url: string) => {
    if (url === '/api/v1/patient/r1') return Promise.resolve({ success: true, data: {
      uuid: 'r1', user_name: 'ساغر صابری', record_number: 'P-1001', created_at: 1700000000,
      user_mobile: '09120000000', user_national_code: '1234567890', tags: [],
      profile: { gender: 'female', referral_source: 'اینستاگرام', address: 'یزد', description: 'یادداشت' },
    } });
    if (url === '/api/v1/patient/r1/sessions') return Promise.resolve({ success: true, data: [
      { uuid: 's1', services: [{ service_name: 'اسکیلینگ' }], doctor_name: 'دکتر فتحی', final_price_rials: 2500000, is_paid: false, patient_debt_rials: 1500000, notes: 'یادداشت', created_at: 1700000000, visit_price_rials: 0 },
      { uuid: 's2', services: [{ service_name: 'روکش' }], doctor_name: 'دکتر فتحی', final_price_rials: 2350000, is_paid: true, patient_debt_rials: 0, invoice_uuid: 'iv1', created_at: 1700000000, visit_price_rials: 0 },
    ], meta: { totalRecords: 2 } });
    if (url === '/api/v1/billing/invoices/iv1') return Promise.resolve({ success: true, data: { data: {
      uuid: 'iv1', status: 'paid', issued_at: 1700000000, total_rials: 2350000,
      base_insurance_rials: 0, supplementary_rials: 0, patient_rials: 2350000,
      items: [{ uuid: 'it1', title: 'روکش', quantity: 1, total_rials: 2350000, patient_rials: 2350000 }],
    } } });
    if (url === '/api/v1/patient/r1/payments') return Promise.resolve({ success: true, data: [
      { uuid: 'p1', amount_rials: 250000, status: 'success', gateway: 'mellat', created_at: 1700000000 },
    ], meta: { totalRecords: 1 } });
    if (url === '/api/v1/patient/r1/wallet') return Promise.resolve({ success: true, data: {
      balance_rials: 300000,
      recent_transactions: [{ uuid: 't1', amount_rials: 500000, type: 'credit', description: 'شارژ', balance_after: 300000, created_at: 1700000000 }],
    } });
    return Promise.resolve({ success: true, data: [] });
  });
});

function renderDetail() {
  return renderWithProviders(
    <Routes>
      <Route path="/admin/patients/:uuid" element={<PatientDetailPage />} />
    </Routes>,
    { route: '/admin/patients/r1' },
  );
}

// name now appears in both breadcrumb and banner
const loaded = async () => (await screen.findAllByText('ساغر صابری'))[0];

describe('PatientDetailPage (پرونده تب‌دار)', () => {
  it('renders the banner and tab bar', async () => {
    renderDetail();
    await loaded();
    expect(screen.getByText('شماره پرونده: P-1001')).toBeInTheDocument(); // banner
    expect(screen.getByText('سرویس‌ها')).toBeInTheDocument();
    expect(screen.getByText('پرونده پزشکی')).toBeInTheDocument();
  });

  it('renders session (مراجعه) cards on the default services tab', async () => {
    renderDetail();
    await loaded();
    expect(await screen.findByText('اسکیلینگ')).toBeInTheDocument();
    expect(screen.getAllByText('دکتر فتحی').length).toBe(2);
    expect(screen.getByText('تکمیل پرداخت')).toBeInTheDocument();  // unpaid card
    expect(screen.getByText('مشاهده فاکتور')).toBeInTheDocument();  // paid card
  });

  it('opens the invoice summary on «مشاهده فاکتور»', async () => {
    renderDetail();
    await screen.findByText('مشاهده فاکتور');
    fireEvent.click(screen.getByText('مشاهده فاکتور'));
    expect(await screen.findByText('خلاصه فاکتور')).toBeInTheDocument();
    expect(await screen.findByText('اطلاعات فاکتور')).toBeInTheDocument();
  });

  it('shows patient info on the info tab', async () => {
    renderDetail();
    await loaded();
    fireEvent.click(screen.getByText('اطلاعات پرونده'));
    expect(screen.getByText('کد ملی')).toBeInTheDocument();
    expect(screen.getByText('1234567890')).toBeInTheDocument();
    expect(screen.getByText('اینستاگرام')).toBeInTheDocument();
  });

  it('renders the call-center tab with a register form and history', async () => {
    renderDetail();
    await loaded();
    fireEvent.click(screen.getByText('کال سنتر'));
    expect(await screen.findByText('ثبت تماس جدید')).toBeInTheDocument();
    expect(screen.getByText('تاریخچه تماس‌ها')).toBeInTheDocument();
    expect(await screen.findByText('تماسی ثبت نشده است.')).toBeInTheDocument();
  });

  it('links "سرویس جدید" on the services tab to the new-session route', async () => {
    renderDetail();
    await loaded();
    const link = await screen.findByRole('link', { name: /سرویس جدید/ });
    expect(link).toHaveAttribute('href', '/admin/patients/r1/session/new');
  });

  it('lists patient payments with status label on the payments tab', async () => {
    renderDetail();
    await loaded();
    fireEvent.click(screen.getByText('پرداخت‌ها'));
    expect(await screen.findByText('موفق')).toBeInTheDocument();
    expect(screen.getByText(/mellat/)).toBeInTheDocument();
  });

  it('shows wallet balance on the wallet tab', async () => {
    renderDetail();
    await loaded();
    fireEvent.click(screen.getByText('کیف پول'));
    expect(await screen.findByText('موجودی کیف پول')).toBeInTheDocument();
    expect(await screen.findByText('شارژ')).toBeInTheDocument();
  });

  it('renders the messages tab with a send box', async () => {
    renderDetail();
    await loaded();
    fireEvent.click(screen.getByText('پیام‌ها'));
    expect(await screen.findByPlaceholderText('متن پیام...')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'ارسال' })).toBeInTheDocument();
  });
});
