import React, { useState } from 'react';
import { Tooltip } from 'antd';
import { IoSettingsOutline } from 'react-icons/io5';
import { DefaultModal } from '../../Components/Modal/DefaultModal.jsx';


const SettingsIconWithModal = ({
  tooltipTitle = 'Add Fields',
  tableFieldPreferences = [],
  selectedAdditionalColumn = [],
  onSubmit,
}) => {
  const [open, setOpen] = useState(false);
  const [selectedFields, setSelectedFields] = useState([]);
  const [tempSelectedColumns, setTempSelectedColumns] = useState([]);

  const handleIconClick = () => {
    // map labels → values
    const mappedFields = selectedAdditionalColumn
      .map(
        (col) =>
          tableFieldPreferences.find((pref) => pref.label === col)?.value
      )
      .filter(Boolean);

    setSelectedFields(mappedFields);
    setTempSelectedColumns([...selectedAdditionalColumn]);
    setOpen(true);
  };

  const handleCancel = () => {
    setOpen(false);
    setTempSelectedColumns([]);
  };

  const handleApply = () => {
    onSubmit({
      selectedFields,
      tempSelectedColumns,
      closeModal: () => setOpen(false),
      resetTemp: () => setTempSelectedColumns([]),
    });
  };

  return (
    <>
      {/* ⚙️ ICON ONLY */}
      <Tooltip title={tooltipTitle} placement="top">
        <IoSettingsOutline
          style={{ cursor: 'pointer', fontSize: '15px' }}
          onClick={handleIconClick}
        />
      </Tooltip>

      {/* MODAL */}
      <DefaultModal
        title="Select Additional Fields"
        open={open}
        footer
        buttonText="Apply"
        destroyOnClose
        handleSubmit={handleApply}
        handleCancel={handleCancel}
      >
        <div style={{ padding: '20px' }}>
          {tableFieldPreferences.map((option) => (
            <div key={option.value} className="Customized_QuickAdd">
              <label>
                <input
                  type="checkbox"
                  checked={selectedFields.includes(option.value)}
                  onChange={(e) => {
                    const checked = e.target.checked;

                    setSelectedFields((prev) =>
                      checked
                        ? [...prev, option.value]
                        : prev.filter((v) => v !== option.value)
                    );

                    setTempSelectedColumns((prev) =>
                      checked
                        ? [...prev, option.label]
                        : prev.filter((v) => v !== option.label)
                    );
                  }}
                  style={{ marginRight: '8px' }}
                />
                {option.label}
              </label>
            </div>
          ))}
        </div>
      </DefaultModal>
    </>
  );
};

export default SettingsIconWithModal;
