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

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

import { api } from '../lib/api';
import TenantInsuranceContracts, { filterInsurances } from './TenantInsuranceContracts';
import type { Contract } from './InsuranceModal';

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

const mk = (over: Partial<Contract>): Contract => ({
  uuid: 'u', insurance_id: 3, insurance_name: 'بیمه ایران', insurance_kind: 'basic',
  version: 1, is_active: true, coverage_percent: 70, franchise_rials: 0,
  annual_ceiling_rials: null, kind: 'basic', effective_from: 0, effective_to: null, ...over,
});

describe('filterInsurances', () => {
  const list = [
    mk({ uuid: 'a', insurance_id: 3, insurance_name: 'بیمه ایران' }),
    mk({ uuid: 'b', insurance_id: 5, insurance_name: 'بیمه آسیا' }),
  ];
  it('filters by name', () => {
    expect(filterInsurances(list, 'آسیا')).toHaveLength(1);
    expect(filterInsurances(list, 'آسیا')[0].uuid).toBe('b');
  });
  it('filters by code (insurance_id)', () => {
    expect(filterInsurances(list, '5')).toHaveLength(1);
  });
  it('empty query returns all', () => {
    expect(filterInsurances(list, '  ')).toHaveLength(2);
  });
});

describe('TenantInsuranceContracts', () => {
  beforeEach(() => {
    get.mockReset();
    patch.mockReset();
    patch.mockResolvedValue({ success: true, data: { data: {} } });
    get.mockImplementation((path: string) => {
      if (path.includes('tenant-insurances')) {
        return Promise.resolve({ success: true, data: { data: [
          mk({ uuid: 'u1', insurance_id: 3, insurance_name: 'بیمه ایران', is_active: true }),
          mk({ uuid: 'u2', insurance_id: 5, insurance_name: 'بیمه آسیا', is_active: false }),
        ] } });
      }
      return Promise.resolve({ success: true, data: { insurances: [] } });
    });
  });

  // Desktop table and mobile cards both render in jsdom (CSS `hidden`/`md:` is inert),
  // so each row's text appears twice — assertions use *AllBy* accordingly.
  it('lists active and inactive contracts', async () => {
    renderWithProviders(<TenantInsuranceContracts />);
    expect((await screen.findAllByText('بیمه ایران')).length).toBeGreaterThan(0);
    expect(screen.getAllByText('بیمه آسیا').length).toBeGreaterThan(0);
  });

  it('search box filters rows by name', async () => {
    renderWithProviders(<TenantInsuranceContracts />);
    await screen.findAllByText('بیمه ایران');
    fireEvent.change(screen.getByPlaceholderText('جستجو در بیمه ها...'), { target: { value: 'آسیا' } });
    expect(screen.queryByText('بیمه ایران')).not.toBeInTheDocument();
    expect(screen.getAllByText('بیمه آسیا').length).toBeGreaterThan(0);
  });

  it('status toggle PATCHes is_active', async () => {
    renderWithProviders(<TenantInsuranceContracts />);
    await screen.findAllByText('بیمه ایران');
    // The active row's toggle offers to deactivate it.
    const toggles = screen.getAllByLabelText('غیرفعال کردن');
    fireEvent.click(toggles[0]);
    await waitFor(() =>
      expect(patch).toHaveBeenCalledWith('/api/v1/billing/tenant-insurances/u1', { is_active: false }),
    );
  });
});
