import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import FeesSection from '@/components/Structure/Tarification/FeesSection';

/* eslint-disable react/display-name */

// Mock du contexte établissement
jest.mock('@/context/EstablishmentContext', () => ({
  useEstablishment: () => ({ selectedEstablishmentId: 1 }),
}));

// Mock des composants UI pour isoler les tests unitaires
jest.mock(
  '@/components/Table',
  () =>
    ({ data, columns, renderCell, emptyMessage }) => {
      if (!data || data.length === 0)
        return <div data-testid="empty-message">{emptyMessage}</div>;
      return (
        <table>
          <tbody>
            {data.map((row) => (
              <tr key={row.id}>
                {columns.map((col) => (
                  <td key={col.name}>{renderCell(row, col.name)}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      );
    }
);

jest.mock(
  '@/components/Popup',
  () =>
    ({ isOpen, message, onConfirm, onCancel }) =>
      isOpen ? (
        <div data-testid="popup">
          <p>{message}</p>
          <button onClick={onConfirm}>Confirmer</button>
          <button onClick={onCancel}>Annuler</button>
        </div>
      ) : null
);

jest.mock('@/components/SectionHeader', () => ({ title, button, onClick }) => (
  <div>
    <h2 className="font-headline">{title}</h2>
    {button && <button onClick={onClick}>Ajouter</button>}
  </div>
));

jest.mock('@/components/AlertMessage', () => ({ title, message }) => (
  <div data-testid="alert-message">
    <strong>{title}</strong>
    <p>{message}</p>
  </div>
));

jest.mock(
  '@/components/Form/InputText',
  () =>
    ({ name, value, onChange, placeholder }) => (
      <input
        name={name}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
      />
    )
);

jest.mock('@/components/Form/CheckBox', () => ({ item, handleChange }) => (
  <input type="checkbox" onChange={handleChange} />
));

jest.mock('@/utils/logger', () => ({
  error: jest.fn(),
  debug: jest.fn(),
}));

const mockFee = {
  id: 1,
  name: 'Frais test',
  base_amount: '200.00',
  description: 'Description test',
  updated_at_formatted: '01-01-2026 10:00',
  is_active: true,
  discounts: [],
  type: 0,
};

describe('FeesSection - type inscription (type=0)', () => {
  const defaultProps = {
    fees: [mockFee],
    setFees: jest.fn(),
    handleCreate: jest.fn(),
    handleEdit: jest.fn(),
    handleDelete: jest.fn(),
    type: 0,
  };

  it('affiche le titre "Liste des frais"', () => {
    render(<FeesSection {...defaultProps} />);
    expect(screen.getByText('Liste des frais')).toBeInTheDocument();
  });

  it('affiche les données du frais dans le tableau', () => {
    render(<FeesSection {...defaultProps} />);
    expect(screen.getByText('Frais test')).toBeInTheDocument();
    expect(screen.getByText('200.00 €')).toBeInTheDocument();
  });

  it('affiche le bouton Ajouter en mode gestion', () => {
    render(<FeesSection {...defaultProps} />);
    expect(screen.getByText('Ajouter')).toBeInTheDocument();
  });

  it('affiche le message vide quand la liste est vide', () => {
    render(<FeesSection {...defaultProps} fees={[]} />);
    expect(screen.getByTestId('empty-message')).toBeInTheDocument();
    expect(screen.getByText('Aucun frais enregistré')).toBeInTheDocument();
  });
});

describe('FeesSection - type scolarité (type=1)', () => {
  const defaultProps = {
    fees: [{ ...mockFee, type: 1 }],
    setFees: jest.fn(),
    handleCreate: jest.fn(),
    handleEdit: jest.fn(),
    handleDelete: jest.fn(),
    type: 1,
  };

  it('affiche le titre "Liste des frais" aussi pour type=1', () => {
    render(<FeesSection {...defaultProps} />);
    expect(screen.getByText('Liste des frais')).toBeInTheDocument();
  });

  it('affiche le message vide générique quand la liste est vide', () => {
    render(<FeesSection {...defaultProps} fees={[]} />);
    expect(screen.getByText('Aucun frais enregistré')).toBeInTheDocument();
  });
});

describe('FeesSection - mode sélection (subscriptionMode)', () => {
  const defaultProps = {
    fees: [mockFee],
    setFees: jest.fn(),
    handleCreate: jest.fn(),
    handleEdit: jest.fn(),
    handleDelete: jest.fn(),
    type: 0,
    subscriptionMode: true,
    selectedFees: [],
    handleFeeSelection: jest.fn(),
  };

  it('cache le header section en mode subscription', () => {
    render(<FeesSection {...defaultProps} />);
    expect(screen.queryByText('Liste des frais')).not.toBeInTheDocument();
  });

  it("n'affiche pas le bouton Ajouter en mode subscription", () => {
    render(<FeesSection {...defaultProps} />);
    expect(screen.queryByText('Ajouter')).not.toBeInTheDocument();
  });
});

describe("FeesSection - création d'un nouveau frais", () => {
  it('initialise le nouveau frais avec le bon type', () => {
    const setFees = jest.fn();
    const handleCreate = jest.fn(() =>
      Promise.resolve({ id: 2, name: 'Nouveau', base_amount: '100' })
    );

    render(
      <FeesSection
        fees={[]}
        setFees={setFees}
        handleCreate={handleCreate}
        handleEdit={jest.fn()}
        handleDelete={jest.fn()}
        type={0}
      />
    );

    fireEvent.click(screen.getByText('Ajouter'));
    // Le nouveau frais doit apparaître dans le tableau
    expect(screen.queryByPlaceholderText('Nom des frais')).toBeInTheDocument();
  });

  it('initialise le nouveau frais avec type=1 pour les frais de scolarité', () => {
    render(
      <FeesSection
        fees={[]}
        setFees={jest.fn()}
        handleCreate={jest.fn()}
        handleEdit={jest.fn()}
        handleDelete={jest.fn()}
        type={1}
      />
    );

    fireEvent.click(screen.getByText('Ajouter'));
    expect(screen.queryByPlaceholderText('Nom des frais')).toBeInTheDocument();
  });
});
