import { useState } from 'react';
import { Icon } from '../../Atoms/Icon/Icon';

export const Accordion = ({
  items = [],
  allowMultiple = false,
  defaultOpen = [],
  className = '',
  ...props
}) => {
  const [openItems, setOpenItems] = useState(defaultOpen);

  const toggleItem = (index) => {
    if (allowMultiple) {
      setOpenItems((prev) =>
        prev.includes(index)
          ? prev.filter((i) => i !== index)
          : [...prev, index]
      );
    } else {
      setOpenItems((prev) => (prev.includes(index) ? [] : [index]));
    }
  };

  if (items.length === 0) return null;

  return (
    <div className={`space-y-2 ${className}`} {...props}>
      {items.map((item, index) => {
        const isOpen = openItems.includes(index);
        return (
          <div key={index} className="border border-gray-200 rounded-lg overflow-hidden">
            <button
              onClick={() => toggleItem(index)}
              className="w-full px-4 py-3 flex items-center justify-between bg-white hover:bg-gray-50 transition-colors"
            >
              <span className="font-medium text-gray-900">{item.title}</span>
              <Icon
                name="ChevronDownIcon"
                className={`h-5 w-5 text-gray-500 transition-transform ${
                  isOpen ? 'transform rotate-180' : ''
                }`}
              />
            </button>
            {isOpen && (
              <div className="px-4 py-3 bg-gray-50 border-t border-gray-200">
                {item.content}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
};

export default Accordion;

