import { Fragment } from 'react/jsx-runtime';
import styles from './CheckListItem.module.css';
import { useEffect, useRef } from 'react';

const CheckListItem = (props: any) => {

    const {
        ele,
        editingTodoId,
        editableTitle,
        editTodo,
        toggleTodo,
        setEditableTitle,
        onSaveEdit,
        todoList,
        index,
        onDeleteTodo
    } = props;

    const textareaRef = useRef<any>(null);
    useEffect(() => {
        const textarea = textareaRef.current;
        if (textarea) {
            textarea.style.height = textarea.scrollHeight + 'px'; 
        }
    }, [editableTitle, editingTodoId]);

    return (
        <Fragment key={ele.id}>
            <div className={styles['checklist-item']}>
                <div
                    className={styles['checklist-item__content']}
                    onClick={() => editTodo(ele.id)}
                >
                    <input
                        type='checkbox'
                        checked={ele.completed}
                        className={styles['custom-checkbox']}
                        onClick={(e) => e.stopPropagation()}
                        onChange={(e) => toggleTodo(ele, e)}
                    />
                    {editingTodoId === ele.id ? (
                        <textarea
                            value={editableTitle}
                            ref={textareaRef}
                            className={styles['checklist-item__editable-input']}
                            onChange={(e) => setEditableTitle(e.target.value)}
                        />
                    ) : (
                        <h3 className={`${styles['checklist-item__title']} ${ele.completed ? styles['strike'] : ''}`} >{ele.title}</h3>
                    )}
                </div>
                <div className=''>
                    {editingTodoId === ele.id ?
                        <img
                            onClick={(e) => onSaveEdit(e, ele.id)}
                            src='../src/assets/images/tick-circle-svgrepo-com.svg'
                            width={25}
                        /> :
                        <img
                            className={styles['checklist-item__remove-btn']}
                            width={30} src='../src/assets/images/close-round-svgrepo-com.svg'
                            onClick={() => onDeleteTodo(ele)}
                        />}
                </div>
            </div>
            {index + 1 !== todoList.length && <hr className={styles.divider} />}
        </Fragment>
    )
}

export default CheckListItem;