import { useRef, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import clsx from '../../../utils/clsx';
import { Icon } from '../../atoms';

export const Accordion = ({
    id,
    style,
    className = '',
    title = __('title', 'rewind-form-bridge-for-brevo'),
    rounded = 'lg',
    defaultOpen = false,
    arrow = true,
    disabled = false,
    single = true,
    children,
}) => {
    const [isOpen, setIsOpen] = useState(defaultOpen);
    const contentRef = useRef(null);
    const [height, setHeight] = useState('0px');

    useEffect(() => {
        if (isOpen && contentRef.current) {
            setHeight(`${contentRef.current.scrollHeight}px`);
        } else {
            setHeight('0px');
        }
    }, [isOpen]);

    const classes = clsx(
        'rbfb-accordion',
        `rounded-${rounded}`,
        single && 'rbfb-accordion--single',
        disabled && 'rbfb-accordion--disabled',
        isOpen && 'rbfb-accordion--open',
        className,
    );

    return (
        <div id={id} style={style} className={classes}>
            <button
                className="rbfb-accordion__header"
                type="button"
                onClick={() => !disabled && setIsOpen((prev) => !prev)}
                aria-expanded={isOpen}
                disabled={disabled}
            >
                <span className="rbfb-accordion__header-title">{title}</span>
                {arrow && (
                    <span
                        className={clsx(
                            'rbfb-accordion__header-icon',
                            isOpen && 'rbfb-accordion__header-icon--open',
                        )}
                    >
                        <Icon name="keyboard_arrow_down" fontSize="2xl" />
                    </span>
                )}
            </button>
            <div
                className="rbfb-accordion__body"
                ref={contentRef}
                style={{
                    maxHeight: height,
                    overflow: 'hidden',
                    transition: 'max-height 0.3s ease',
                }}
            >
                <div className="rbfb-accordion__body-inner">{children}</div>
            </div>
        </div>
    );
};

export const AccordionGroup = ({ items, allowMultiple = true }) => {
    const [openIds, setOpenIds] = useState([]);
    const contentRefs = useRef({});

    const handleToggle = (id) => {
        setOpenIds((prev) =>
            prev.includes(id)
                ? prev.filter((i) => i !== id)
                : allowMultiple
                ? [...prev, id]
                : [id],
        );
    };

    return (
        <div className="rbfb-accordion-group">
            {items.map(({ id, title, content, disabled }) => {
                const isOpen = openIds.includes(id);
                const height =
                    isOpen && contentRefs.current[id]
                        ? `${contentRefs.current[id].scrollHeight}px`
                        : '0px';

                const itemCls = clsx(
                    'rbfb-accordion',
                    isOpen && 'rbfb-accordion--open',
                    disabled && 'rbfb-accordion--disabled',
                );

                return (
                    <div key={id} className={itemCls}>
                        <button
                            className="rbfb-accordion__header"
                            type="button"
                            onClick={() => !disabled && handleToggle(id)}
                            aria-expanded={isOpen}
                            disabled={disabled}
                        >
                            <span className="rbfb-accordion__header-title">
                                {title}
                            </span>
                            <span className="rbfb-accordion__header-icon">
                                <Icon
                                    name="keyboard_arrow_down"
                                    fontSize="2xl"
                                />
                            </span>
                        </button>

                        <div
                            className="rbfb-accordion__body"
                            style={{
                                maxHeight: height,
                                overflow: 'hidden',
                                transition: 'max-height 0.3s ease',
                            }}
                        >
                            <div
                                className="rbfb-accordion__body-inner"
                                ref={(el) => {
                                    contentRefs.current[id] = el;
                                }}
                            >
                                {content}
                            </div>
                        </div>
                    </div>
                );
            })}
        </div>
    );
};
