import React, { useEffect } from 'react';
import SelectChoice from '@/components/Form/SelectChoice';
import RadioList from '@/components/Form/RadioList';
import logger from '@/utils/logger';

export default function PaymentMethodSelector({
  formData,
  setFormData,
  registrationPaymentModes,
  tuitionPaymentModes,
  registrationPaymentPlans,
  tuitionPaymentPlans,
  errors,
  setIsPageValid,
  enable = true,
}) {
  useEffect(() => {
    const isValid = !Object.keys(formData).some(
      (field) => getLocalError(field) !== ''
    );
    setIsPageValid(isValid);
    logger.debug('formdata : ', formData);
  }, [formData, setIsPageValid]);

  const paymentModesOptions = [
    { id: 1, name: 'Prélèvement SEPA' },
    { id: 2, name: 'Virement' },
    { id: 3, name: 'Chèque' },
    { id: 4, name: 'Espèce' },
  ];

  const paymentPlansOptions = [
    { id: 1, name: '1 fois' },
    { id: 2, name: '3 fois' },
    { id: 3, name: '10 fois' },
    { id: 4, name: '12 fois' },
  ];

  const getError = (field) => {
    return errors?.student?.[field]?.[0];
  };

  const getLocalError = (field) => {
    if (
      (field === 'registration_payment' &&
        (!formData.registration_payment ||
          String(formData.registration_payment).trim() === '')) ||
      (field === 'tuition_payment' &&
        (!formData.tuition_payment ||
          String(formData.tuition_payment).trim() === '')) ||
      (field === 'registration_payment_plan' &&
        (!formData.registration_payment_plan ||
          String(formData.registration_payment_plan).trim() === '')) ||
      (field === 'tuition_payment_plan' &&
        (!formData.tuition_payment_plan ||
          String(formData.tuition_payment_plan).trim() === ''))
    ) {
      return 'Champs requis';
    }
    return '';
  };

  const onChange = (field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  // Fonction utilitaire pour trier selon paymentPlansOptions
  const sortPlansByOptions = (plans, options) => {
    const order = options.map((opt) => opt.id);
    return [...plans].sort(
      (a, b) => order.indexOf(a.plan_type) - order.indexOf(b.plan_type)
    );
  };

  return (
    <>
      {/* Frais d'inscription */}
      <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
        <h2 className="font-headline text-2xl font-semibold mb-6 text-gray-800 border-b pb-2">
          Frais d&apos;inscription
        </h2>

        <div className="mb-6 bg-gray-50 p-4 rounded-lg border border-gray-100">
          <p className="text-gray-700 text-sm mb-2">
            <strong className="text-gray-900">Montant :</strong>{' '}
            {formData.totalRegistrationFees} €
          </p>
        </div>

        <SelectChoice
          name="registration_payment"
          label="Mode de Paiement"
          placeHolder="Sélectionner un mode de paiement"
          selected={formData.registration_payment}
          callback={(e) => {
            const selectedId = parseInt(e.target.value, 10);
            const selectedMode = registrationPaymentModes.find(
              (mode) => mode.id === selectedId
            );
            // Pour le mode de paiement d'inscription
            onChange('registration_payment', selectedId);
            // Ajoute ou retire isSepa selon le mode choisi
            if (selectedMode && selectedMode.mode === 1) {
              onChange('isSepa', 1);
            } else {
              // Vérifie si le mode de paiement scolarité n'est pas SEPA
              const tuitionMode = tuitionPaymentModes.find(
                (mode) => mode.id === formData.tuition_payment
              );
              if (!tuitionMode || tuitionMode.mode !== 1) {
                onChange('isSepa', 0);
              }
            }
          }}
          choices={registrationPaymentModes.map((mode) => ({
            value: mode.id, // <-- utiliser l'id du mode de paiement
            label:
              paymentModesOptions.find((option) => option.id === mode.mode)
                ?.name || 'Mode inconnu',
          }))}
          errorMsg={getError('registration_payment')}
          errorLocalMsg={getLocalError('registration_payment')}
          required
          disabled={!enable}
        />

        <RadioList
          sectionLabel="Choisissez une option"
          required
          items={sortPlansByOptions(
            registrationPaymentPlans,
            paymentPlansOptions
          ).map((plan) => ({
            id: plan.id,
            label:
              paymentPlansOptions.find((opt) => opt.id === plan.plan_type)
                ?.name || `Option ${plan.plan_type}`,
          }))}
          formData={{
            ...formData,
            registration_payment_plan: parseInt(
              formData.registration_payment_plan,
              10
            ),
          }}
          handleChange={(e) => {
            const value = parseInt(e.target.value, 10);
            onChange('registration_payment_plan', value);
          }}
          fieldName="registration_payment_plan"
          className="mt-4"
          disabled={!enable}
        />
      </div>

      {/* Frais de scolarité */}
      <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 mt-12">
        <h2 className="font-headline text-2xl font-semibold mb-6 text-gray-800 border-b pb-2">
          Frais de scolarité
        </h2>

        <div className="mb-6 bg-gray-50 p-4 rounded-lg border border-gray-100">
          <p className="text-gray-700 text-sm mb-2">
            <strong className="text-gray-900">Montant :</strong>{' '}
            {formData.totalTuitionFees} €
          </p>
        </div>

        <SelectChoice
          name="tuition_payment"
          label="Mode de Paiement"
          placeHolder="Sélectionner un mode de paiement"
          selected={formData.tuition_payment}
          callback={(e) => {
            const selectedId = parseInt(e.target.value, 10);
            const selectedMode = tuitionPaymentModes.find(
              (mode) => mode.id === selectedId
            );
            // Pour le mode de paiement de scolarité
            onChange('tuition_payment', selectedId);
            // Ajoute ou retire isSepa selon le mode choisi
            if (selectedMode && selectedMode.mode === 1) {
              onChange('isSepa', 1);
            } else {
              // Vérifie si le mode de paiement inscription n'est pas SEPA
              const registrationMode = registrationPaymentModes.find(
                (mode) => mode.id === formData.registration_payment
              );
              if (!registrationMode || registrationMode.mode !== 1) {
                onChange('isSepa', 0);
              }
            }
          }}
          choices={tuitionPaymentModes.map((mode) => ({
            value: mode.id,
            label:
              paymentModesOptions.find((option) => option.id === mode.mode)
                ?.name || 'Mode inconnu',
          }))}
          errorMsg={getError('tuition_payment')}
          errorLocalMsg={getLocalError('tuition_payment')}
          required
          disabled={!enable}
        />

        <RadioList
          sectionLabel="Choisissez une option"
          required
          items={sortPlansByOptions(
            tuitionPaymentPlans,
            paymentPlansOptions
          ).map((plan) => ({
            id: plan.id,
            label:
              paymentPlansOptions.find((opt) => opt.id === plan.plan_type)
                ?.name || `Option ${plan.plan_type}`,
          }))}
          formData={{
            ...formData,
            tuition_payment_plan: parseInt(formData.tuition_payment_plan, 10),
          }}
          handleChange={(e) => {
            const value = parseInt(e.target.value, 10); // valeur = id du plan
            onChange('tuition_payment_plan', value);
          }}
          fieldName="tuition_payment_plan"
          className="mt-4"
          errorMsg={
            getError('tuition_payment_plan') ||
            getLocalError('tuition_payment_plan')
          }
          disabled={!enable}
        />
      </div>
    </>
  );
}
