import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import AdhesionPage from '../page';

// Mock next-intl
jest.mock('next-intl', () => ({
  useTranslations: () => (key: string) => {
    const translations: Record<string, string> = {
      page_title: 'Adhésion en ligne',
      type_label: "Type d'adhérent",
      type_particulier: 'Particulier',
      type_association: 'Association',
      type_entreprise: 'Entreprise',
      cotisation_label: 'Cotisation',
      cotisation_classique: 'Classique — 10€',
      cotisation_soutien: 'Soutien — 30€',
      cotisation_libre: 'Libre',
      amount_placeholder: 'Montant libre (min. 10€)',
      amount_min_error: 'Le montant minimum est de 10€',
      fiscal_title: 'Réduction fiscale',
      fiscal_donation: 'Votre don',
      fiscal_reduction: "Réduction d'impôt (66%)",
      fiscal_real_cost: 'Coût réel',
      info_label: 'Informations personnelles',
      first_name: 'Prénom',
      last_name: 'Nom',
      address: 'Adresse',
      address2: 'Adresse (ligne 2)',
      postal_code: 'Code postal',
      city: 'Ville',
      email: 'Email',
      options_label: 'Options',
      wants_receipt: 'Je souhaite recevoir un reçu fiscal',
      wants_member_card: 'Recevoir une carte adhérent',
      member_card_yes: 'Oui',
      member_card_no: 'Non',
      submit_button: 'Adhérer',
      payment_title: 'Paiement sécurisé',
      required_field: 'Ce champ est requis',
      loading: 'Chargement...',
    };
    return translations[key] || key;
  },
}));

// Mock adhesionService
const mockInitPayment = jest.fn();
jest.mock('@/services/adhesionService', () => ({
  initPayment: (...args: unknown[]) => mockInitPayment(...args),
}));

// Mock next/script
jest.mock('next/script', () => ({
  __esModule: true,
  default: () => null,
}));

describe('AdhesionPage', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('shouldRenderAdherentTypeSelection', () => {
    render(<AdhesionPage />);
    expect(screen.getByText("Type d'adhérent")).toBeInTheDocument();
    expect(screen.getByLabelText('Particulier')).toBeInTheDocument();
    expect(screen.getByLabelText('Association')).toBeInTheDocument();
    expect(screen.getByLabelText('Entreprise')).toBeInTheDocument();
  });

  it('shouldRenderCotisationOptionsWithAmounts', () => {
    render(<AdhesionPage />);
    expect(screen.getByText('Cotisation')).toBeInTheDocument();
    expect(screen.getByLabelText('Classique — 10€')).toBeInTheDocument();
    expect(screen.getByLabelText('Soutien — 30€')).toBeInTheDocument();
    expect(screen.getByLabelText('Libre')).toBeInTheDocument();
  });

  it('shouldShowFreeAmountInputWhenLibreSelected', () => {
    render(<AdhesionPage />);
    expect(screen.queryByPlaceholderText('Montant libre (min. 10€)')).not.toBeInTheDocument();

    fireEvent.click(screen.getByLabelText('Libre'));
    expect(screen.getByPlaceholderText('Montant libre (min. 10€)')).toBeInTheDocument();
  });

  it('shouldCalculateFiscalReductionWhenReceiptChecked', () => {
    render(<AdhesionPage />);

    // Select soutien (30€)
    fireEvent.click(screen.getByLabelText('Soutien — 30€'));
    // Check receipt
    fireEvent.click(screen.getByLabelText('Je souhaite recevoir un reçu fiscal'));

    expect(screen.getByText(/19,80\s*€/)).toBeInTheDocument(); // 30 * 0.66
    expect(screen.getByText(/10,20\s*€/)).toBeInTheDocument(); // 30 * 0.34
  });

  it('shouldValidateRequiredFieldsBeforeSubmit', async () => {
    render(<AdhesionPage />);

    const submitBtn = screen.getByRole('button', { name: /adhérer/i });
    fireEvent.click(submitBtn);

    // Form should not submit — initPayment should not be called
    expect(mockInitPayment).not.toHaveBeenCalled();
  });

  it('shouldValidateMinimumAmount', () => {
    render(<AdhesionPage />);

    fireEvent.click(screen.getByLabelText('Libre'));
    const amountInput = screen.getByPlaceholderText('Montant libre (min. 10€)');
    fireEvent.change(amountInput, { target: { value: '5' } });

    const submitBtn = screen.getByRole('button', { name: /adhérer/i });
    fireEvent.click(submitBtn);

    expect(mockInitPayment).not.toHaveBeenCalled();
  });

  it('shouldSubmitFormAndShowPaymentWidget', async () => {
    mockInitPayment.mockResolvedValueOnce({ success: true, token: 'TOKEN_123' });

    render(<AdhesionPage />);

    // Fill form
    fireEvent.click(screen.getByLabelText('Particulier'));
    fireEvent.click(screen.getByLabelText('Classique — 10€'));
    fireEvent.change(screen.getByLabelText('Prénom'), { target: { value: 'Jean' } });
    fireEvent.change(screen.getByLabelText('Nom'), { target: { value: 'Dupont' } });
    fireEvent.change(screen.getByLabelText('Adresse'), { target: { value: '12 rue de Brest' } });
    fireEvent.change(screen.getByLabelText('Code postal'), { target: { value: '29000' } });
    fireEvent.change(screen.getByLabelText('Ville'), { target: { value: 'Quimper' } });
    fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'jean@example.com' } });

    const submitBtn = screen.getByRole('button', { name: /adhérer/i });
    fireEvent.click(submitBtn);

    await waitFor(() => {
      expect(mockInitPayment).toHaveBeenCalledWith(expect.objectContaining({
        type: 'particulier',
        cotisationType: 'classique',
        amount: 1000,
        firstName: 'Jean',
        lastName: 'Dupont',
      }));
    });

    await waitFor(() => {
      expect(screen.getByText('Paiement sécurisé')).toBeInTheDocument();
    });
  });
});
