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

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,
  allPaymentPlans,
  handleCreate,
  handleDelete,
  type,
}) => {
  const { selectedEstablishmentId } = useEstablishment();
  const [checkedPlans, setCheckedPlans] = useState([]);

  const plans = useMemo(
    () =>
      Array.isArray(allPaymentPlans)
        ? allPaymentPlans
        : Array.isArray(paymentPlans)
          ? paymentPlans
          : [],
    [allPaymentPlans, paymentPlans]
  );
  const unified = !!allPaymentPlans;

  const isChecked = (planOption) => checkedPlans.includes(planOption.id);

  const handlePlanToggle = (planOption) => {
    if (isChecked(planOption)) {
      const toDelete = plans.filter(
        (p) =>
          (typeof p.plan_type === 'object' ? p.plan_type.id : p.plan_type) ===
          planOption.id
      );
      setCheckedPlans((prev) => prev.filter((id) => id !== planOption.id));
      toDelete.forEach((p) =>
        handleDelete(p.id, null).catch((e) => logger.error(e))
      );
    } else {
      setCheckedPlans((prev) => [...prev, planOption.id]);
      if (unified) {
        [0, 1].forEach((t) =>
          handleCreate({
            plan_type: planOption.id,
            type: t,
            establishment: selectedEstablishmentId,
          }).catch((e) => logger.error(e))
        );
      } else {
        handleCreate({
          plan_type: planOption.id,
          type,
          establishment: selectedEstablishmentId,
        }).catch((e) => logger.error(e));
      }
    }
  };

  useEffect(() => {
    if (plans.length > 0) {
      const ids = plans.map((plan) =>
        typeof plan.plan_type === 'object' ? plan.plan_type.id : plan.plan_type
      );
      setCheckedPlans([...new Set(ids)]);
    } else {
      setCheckedPlans([]);
    }
  }, [plans]);

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2 mb-3">
        <Calendar className="w-5 h-5 text-primary" />
        <h3 className="font-headline text-base font-semibold text-gray-800">
          Paiement en plusieurs fois
        </h3>
      </div>
      <div className="grid grid-cols-2 gap-3">
        {paymentPlansOptions.map((option) => (
          <button
            key={option.id}
            type="button"
            onClick={() => handlePlanToggle(option)}
            className={`py-2 px-3 rounded border text-sm font-label font-medium text-center transition-colors min-h-[44px] ${
              isChecked(option)
                ? 'bg-primary/10 border-primary text-primary'
                : 'bg-white border-gray-200 text-gray-700 hover:bg-gray-50'
            }`}
          >
            {option.name}
          </button>
        ))}
      </div>
    </div>
  );
};

export default PaymentPlanSelector;
