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

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

const PaymentModeSelector = ({
  paymentModes,
  setPaymentModes,
  handleCreate,
  handleDelete,
  type,
}) => {
  const [activePaymentModes, setActivePaymentModes] = useState([]);
  const { selectedEstablishmentId } = useEstablishment();

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

  const handleModeToggle = (modeId) => {
    const updatedMode = paymentModes.find((mode) => mode.mode === modeId);
    const isActive = !!updatedMode;

    if (!isActive) {
      handleCreate({
        mode: modeId,
        type,
        establishment: selectedEstablishmentId,
      });
    } else {
      handleDelete(updatedMode.id, null);
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center mb-4">
        <DollarSign className="w-6 h-6 text-emerald-500 mr-2" />
        <h2 className="text-xl font-semibold">Modes de paiement</h2>
      </div>
      <div className="grid grid-cols-2 gap-4 mt-4">
        {paymentModesOptions.map((mode) => (
          <button
            key={mode.id}
            type="button"
            onClick={() => handleModeToggle(mode.id)}
            className={`p-4 rounded-lg shadow-md text-center text-gray-700 ${
              activePaymentModes.includes(mode.id)
                ? 'bg-emerald-100'
                : 'bg-stone-50'
            } hover:bg-emerald-200`}
          >
            {mode.name}
          </button>
        ))}
      </div>
    </div>
  );
};

export default PaymentModeSelector;
