import React, { useEffect, useMemo, useState } from 'react';
import { DollarSign } from 'lucide-react';
import { useEstablishment } from '@/context/EstablishmentContext';
import logger from '@/utils/logger';

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

/**
 * Affiche les modes de paiement communs aux deux types de frais.
 * Quand `allPaymentModes` est fourni (mode unifié), un mode activé est créé
 * pour les deux types (inscription 0 ET scolarité 1).
 */
const PaymentModeSelector = ({
  paymentModes,
  allPaymentModes,
  setPaymentModes,
  handleCreate,
  handleDelete,
  type,
}) => {
  const [activePaymentModes, setActivePaymentModes] = useState([]);
  const { selectedEstablishmentId } = useEstablishment();

  const modes = useMemo(
    () =>
      Array.isArray(allPaymentModes)
        ? allPaymentModes
        : Array.isArray(paymentModes)
          ? paymentModes
          : [],
    [allPaymentModes, paymentModes]
  );
  const unified = !!allPaymentModes;

  useEffect(() => {
    const activeModes = [...new Set(modes.map((mode) => mode.mode))];
    setActivePaymentModes(activeModes);
  }, [modes]);

  const handleModeToggle = (modeId) => {
    const isActive = activePaymentModes.includes(modeId);
    if (!isActive) {
      if (unified) {
        [0, 1].forEach((t) =>
          handleCreate({
            mode: modeId,
            type: t,
            establishment: selectedEstablishmentId,
          }).catch((e) => logger.error(e))
        );
      } else {
        handleCreate({
          mode: modeId,
          type,
          establishment: selectedEstablishmentId,
        }).catch((e) => logger.error(e));
      }
    } else {
      const toDelete = modes.filter((m) => m.mode === modeId);
      toDelete.forEach((m) =>
        handleDelete(m.id, null).catch((e) => logger.error(e))
      );
    }
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2 mb-3">
        <DollarSign className="w-5 h-5 text-primary" />
        <h3 className="font-headline text-base font-semibold text-gray-800">
          Modes de paiement
        </h3>
      </div>
      <div className="grid grid-cols-2 gap-3">
        {paymentModesOptions.map((mode) => (
          <button
            key={mode.id}
            type="button"
            onClick={() => handleModeToggle(mode.id)}
            className={`py-2 px-3 rounded border text-sm font-label font-medium text-center transition-colors min-h-[44px] ${
              activePaymentModes.includes(mode.id)
                ? 'bg-primary/10 border-primary text-primary'
                : 'bg-white border-gray-200 text-gray-700 hover:bg-gray-50'
            }`}
          >
            {mode.name}
          </button>
        ))}
      </div>
    </div>
  );
};

export default PaymentModeSelector;
