import '../types/extension';
import {StyleSheet, View} from "react-native";
import {purpleColor} from "../assets/Theme";
import {useDispatch, useSelector} from "react-redux";
import React, {useEffect, useState} from "react";
import {getCustomJokeById, getJokeById} from "../redux/thunk/GetByThunk";
import JokeDetail from "../components/JokeDetail";
import {AppDispatch, AppState} from "../redux/store";
import {CustomJoke} from "../model/CustomJoke";
import {SampleJoke} from "../model/SampleJoke";

export default function JokeDetailsScreen({route}) {
    const idJokeDetail = route.params.idJoke;
    const joke = useSelector<AppState>(state => state.sampleReducer.joke);
    const customJoke = useSelector<AppState>(state => state.customReducer.customJoke);
    const [isCustomJoke, setCustomJoke] = useState(false);
    const dispatch = useDispatch<AppDispatch>();

    useEffect(() => {
        if(typeof idJokeDetail == 'number') {
            const loadJoke = async () => {
                await dispatch(getJokeById(idJokeDetail));
            };
            loadJoke();
            setCustomJoke(!isCustomJoke)
        } else {
            const loadCustomJoke = async () => {
                await dispatch(getCustomJokeById(idJokeDetail));
            };
            loadCustomJoke();
        }
    }, [dispatch]);

    if(!joke && !customJoke) return null;

    return (
        <View style={styles.container}>
            {/*@ts-ignore}*/}
            <JokeDetail joke={isCustomJoke ? joke : customJoke}/>
        </View>
    )
};

const styles = StyleSheet.create({
    container: {
        backgroundColor: purpleColor,
        flex:1,
    }
});