import React, { useState, useEffect } from 'react';
import { Calendar } from 'lucide-react';
import Table from '@/components/Table';
import Popup from '@/components/Popup';
import logger from '@/utils/logger';
import { useEstablishment } from '@/context/EstablishmentContext';
import CheckBox from '@/components/CheckBox';

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

const PaymentPlanSelector = ({
  paymentPlans,
  handleCreate,
  handleDelete,
  type,
}) => {
  const [popupVisible, setPopupVisible] = useState(false);
  const [popupMessage, setPopupMessage] = useState('');
  const { selectedEstablishmentId } = useEstablishment();
  const [checkedPlans, setCheckedPlans] = useState([]);

  // Vérifie si un plan existe pour ce type (par id)
  const isChecked = (planOption) => checkedPlans.includes(planOption.id);

  // Création ou suppression du plan
  const handlePlanToggle = (planOption) => {
    const updatedPlan = paymentPlans.find(
      (plan) => plan.plan_type === planOption.id
    );
    if (isChecked(planOption)) {
      setCheckedPlans((prev) => prev.filter((id) => id !== planOption.id));
      handleDelete(updatedPlan.id, null);
    } else {
      setCheckedPlans((prev) => [...prev, planOption.id]);
      handleCreate({
        plan_type: planOption.id,
        type,
        establishment: selectedEstablishmentId,
      });
    }
  };

  useEffect(() => {
    if (paymentPlans && paymentPlans.length > 0) {
      setCheckedPlans(
        paymentPlans.map((plan) =>
          typeof plan.plan_type === 'object'
            ? plan.plan_type.id
            : plan.plan_type
        )
      );
    }
  }, [paymentPlans]);

  return (
    <div className="space-y-4">
      <div className="flex items-center mb-4">
        <Calendar className="w-6 h-6 text-emerald-500 mr-2" />
        <h2 className="text-xl font-semibold">Paiement en plusieurs fois</h2>
      </div>
      <div className="grid grid-cols-2 gap-4">
        <Table
          data={paymentPlansOptions}
          columns={[
            { name: 'OPTION', label: 'Option' },
            { name: 'ACTIF', label: 'Actif' },
          ]}
          renderCell={(row, column) => {
            switch (column) {
              case 'OPTION':
                return (
                  <span className="text-sm font-medium text-gray-900">
                    {row.name}
                  </span>
                );
              case 'ACTIF':
                return (
                  <CheckBox
                    item={{ id: row.id }}
                    formData={{ checked: isChecked(row) }}
                    handleChange={() => handlePlanToggle(row)}
                    fieldName="checked"
                    itemLabelFunc={() => ''}
                    horizontal={true}
                  />
                );
              default:
                return null;
            }
          }}
        />
      </div>
      <Popup
        isOpen={popupVisible}
        message={popupMessage}
        onConfirm={() => setPopupVisible(false)}
        onCancel={() => setPopupVisible(false)}
        uniqueConfirmButton={true}
      />
    </div>
  );
};

export default PaymentPlanSelector;
