import React, { useState, useEffect } from 'react';
import { Check } from 'lucide-react';
import Popup from '@/components/Popup';
import logger from '@/utils/logger';

const DateTab = ({
  dates,
  activeTab,
  handleDateChange,
  handleEdit,
  type,
  paymentPlanId,
  resetModifiedDates,
}) => {
  const [popupVisible, setPopupVisible] = useState(false);
  const [popupMessage, setPopupMessage] = useState('');
  const [modifiedDates, setModifiedDates] = useState({});

  useEffect(() => {
    if (resetModifiedDates) {
      setModifiedDates({});
    }
  }, [resetModifiedDates]);

  const submit = (updatedData) => {
    const dataWithType = {
      ...updatedData,
      type: type,
    };
    handleEdit(paymentPlanId, dataWithType)
      .then(() => {
        setPopupMessage(
          "Mise à jour de la date d'échéance effectuée avec succès"
        );
        setPopupVisible(true);
        setModifiedDates({});
      })
      .catch((error) => {
        logger.error(error);
      });
  };

  const handleDateChangeWithModification = (tab, index, value) => {
    handleDateChange(tab, index, value);
    setModifiedDates((prev) => ({ ...prev, [`${tab}-${index}`]: true }));
  };

  return (
    <div className="bg-white p-4 rounded-lg h-auto max-h-96 overflow-y-auto">
      <div className="flex flex-col space-y-3">
        {dates[activeTab]?.map((date, index) => (
          <div key={index} className="flex items-center space-x-3">
            <span className="text-secondary font-semibold">
              Échéance {index + 1}
            </span>
            <input
              type="date"
              value={date}
              onChange={(e) =>
                handleDateChangeWithModification(
                  activeTab,
                  index,
                  e.target.value
                )
              }
              className="p-2 border border-primary/30 rounded focus:outline-none focus:ring-2 focus:ring-primary cursor-pointer"
            />
            {modifiedDates[`${activeTab}-${index}`] && (
              <button
                type="button"
                onClick={() =>
                  submit({
                    frequency: dates[activeTab].length,
                    due_dates: dates[activeTab],
                  })
                }
                className="text-primary hover:text-secondary"
              >
                <Check className="w-5 h-5" />
              </button>
            )}
          </div>
        ))}
      </div>
      {popupVisible && (
        <Popup
          isOpen={popupVisible}
          message={popupMessage}
          onConfirm={() => setPopupVisible(false)}
          onCancel={() => setPopupVisible(false)}
          uniqueConfirmButton={true}
        />
      )}
    </div>
  );
};

export default DateTab;
