import * as React from 'react';
import { FunctionComponent, useCallback } from 'react';
import { HiddenInput, List } from 'react-bootstrap-mobile';
import { useAppDispatch, useAppSelector } from '../Store/reduxHooks';
import { removeMember, saveMember, selectMembers } from './prayerCircleSlice';
import { MemberType } from './MemberType';
import { nanoid } from '@reduxjs/toolkit';

type Props = {};

export const MemberList: FunctionComponent<Props> = React.memo(({}) => {
    // Variables
    const dispatch = useAppDispatch();
    const members = useAppSelector((state) => selectMembers(state));
    members.push({
        id: nanoid(),
        name: '',
        usedForBalance: false,
    });

    // States

    // Refs

    // Callbacks
    const keyExtractor = useCallback((item: MemberType) => item.id ?? 'undefined', []);
    const saveChangedMember = useCallback(
        ({ extraData: memberId, target: { value: name } }) => {
            if (name.trim() === '') {
                if (memberId) {
                    dispatch(removeMember(memberId));
                }
            } else {
                dispatch(
                    saveMember({
                        id: memberId,
                        name,
                    })
                );
            }
        },
        [dispatch]
    );

    // Effects

    // Other

    // Render Functions
    const renderMember = useCallback(
        (member: MemberType) => {
            return (
                <HiddenInput
                    key={member.id}
                    noFocusHint={true}
                    value={member.name}
                    placeholder="+ Add Person"
                    onChange={saveChangedMember}
                    onChangeData={member.id}
                />
            );
        },
        [saveChangedMember]
    );

    return <List items={members} renderItem={renderMember} keyExtractor={keyExtractor} />;
});
