// screens/moves/MoveListScreen.tsx

import React, { useEffect }                               from 'react';
import { Button, FlatList, ScrollView, StyleSheet, View } from 'react-native';
import { StackNavigationProp }                            from '@react-navigation/stack';
import { RootStackParamList }                             from "../../navigation/navigationTypes";
import { useDispatch, useSelector }                       from 'react-redux';
import { deleteMove, getMoves }                           from '../../redux/actions/moveActions';
import { MoveState }                                      from "../../redux/reducers/moveReducer";
import { AppDispatch }                                    from "../../redux/store";
import MoveListItem                                       from "../../components/MoveListItem";
import { MOVE_DETAIL, MOVE_FORM, MOVE_LIST }              from "../../navigation/constants";
import { RouteProp }                                      from "@react-navigation/native";

type MoveListScreenNavigationProp = StackNavigationProp<RootStackParamList, typeof MOVE_LIST>;
type MoveListScreenRouteProp = RouteProp<RootStackParamList, typeof MOVE_LIST>;

type Props = {
    navigation: MoveListScreenNavigationProp;
    route: MoveListScreenRouteProp;
};
type RootState = {
    move: MoveState;
};

const MoveListScreen = ({ navigation }: Props) => {
    const dispatch: AppDispatch = useDispatch();
    const moves = useSelector((state: RootState) => state.move.moves);

    useEffect(() => {
        const loadMoves = async () => {
            await (dispatch as AppDispatch)(getMoves());
        };
        loadMoves();
    }, [dispatch, moves]);

    return (
        <ScrollView>
            <Button title="Add Move" onPress={() => navigation.navigate(MOVE_FORM, { move: undefined })}/>
            <View>
                <FlatList
                    data={moves}
                    renderItem={({ item }) => (
                        <View style={styles.listItemContainer}>
                            <MoveListItem
                                move={item}
                                onPress={() => navigation.navigate(MOVE_DETAIL, { move: item })}
                            />
                            <Button title="Delete"
                                    color={styles.deleteButton.backgroundColor}
                                    onPress={() => dispatch(deleteMove(item.id!))}/>
                        </View>
                    )}
                    keyExtractor={(item) => item.name}
                />
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    deleteButton: {
        backgroundColor: '#FF6961',
    },
    listItemContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
});

export default MoveListScreen;
