import crashlytics from '@react-native-firebase/crashlytics';
import { RouteProp } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import React, { useEffect } from 'react';
import { getUniqueId } from 'react-native-device-info';
import { useSelector } from 'react-redux';
import { _map } from './RN-UI-LIB/src/utlis/common';
import { GenericType } from './src/common/GenericTypes';
import Widget from './src/components/form';
import { registerNavigateAndDispatch } from './src/components/utlis/apiHelper';
import { getLoanIdToValueFromLocal } from './src/components/utlis/registerPaymentUtils';
import { setGlobalUserData } from './src/constants/Global';
import { useAppDispatch, useAppSelector } from './src/hooks';
import useFirestoreUpdates from './src/hooks/useFirestoreUpdates';
import { setLoanIdToValue } from './src/reducer/paymentSlice';
import { setDeviceId } from './src/reducer/userSlice';
import AddressGeolocation from './src/screens/addressGeolocation';
import NewAddressContainer from './src/screens/addressGeolocation/NewAddressContainer';
import AllCasesMain from './src/screens/allCases';
import CompletedCase from './src/screens/allCases/CompletedCase';
import CaseDetails from './src/screens/caseDetails/CaseDetails';
import CollectionCaseDetails from './src/screens/caseDetails/CollectionCaseDetail';
import interactionsHandler from './src/screens/caseDetails/interactionsHandler';
import Login from './src/screens/login';
import OtpInput from './src/screens/login/OtpInput';
import Profile from './src/screens/Profile';
import RegisterPayments from './src/screens/registerPayements/RegisterPayments';
import TodoList from './src/screens/todoList/TodoList';
import { RootState } from './src/store/store';
import { CaseAllocationType } from "./src/screens/allCases/interface";
import { getTemplateRoute } from "./src/components/utlis/navigationUtlis";
import { resetNewVisitedCases } from './src/reducer/allCasesSlice';
import { getCaseUnifiedData, UnifiedCaseDetailsTypes } from './src/action/caseApiActions';
import FeedbackDetailContainer from './src/screens/caseDetails/feedback/FeedbackDetailContainer';
import EmiSchedule from './src/screens/emiSchedule';
import { NetworkStatusService } from "./src/services/network-monitoring.service";

const ANIMATION_DURATION = 300;

const Stack = createNativeStackNavigator();

export enum PageRouteEnum {
    PAYMENTS = 'registerPayments',
    ADDRESS_GEO = 'addressGeolocation',
    NEW_ADDRESS = 'newAddress',
    COLLECTION_CASE_DETAIL = 'collectionCaseDetail',
    EMI_SCHEDULE = 'EmiSchedule',
    PAST_FEEDBACK_DETAIL = 'pastFeedbackDetail'
}

const ProtectedRouter = () => {
    const user = useSelector(
        (state: RootState) => state.user,
    );
    const { newVisitedCases, caseDetails } = useAppSelector(state => state.allCases);

    useEffect(() => {
        if(newVisitedCases?.length) {
            const loanAccountNumbers: string[] = [];
            newVisitedCases.forEach(caseId => {
                const { loanAccountNumber } = caseDetails[caseId];
                if(!loanAccountNumber) {
                    return;
                }
                loanAccountNumbers.push(loanAccountNumber);
            });
            if(loanAccountNumbers.length) {
                const { EMI_SCHEDULE, REPAYMENTS, ADDRESS_AND_GEOLOCATIONS, FEEDBACKS } = UnifiedCaseDetailsTypes;
                dispatch(getCaseUnifiedData(loanAccountNumbers, [EMI_SCHEDULE, REPAYMENTS, ADDRESS_AND_GEOLOCATIONS, FEEDBACKS]))
            }
            dispatch(resetNewVisitedCases());
        }
    }, [newVisitedCases])

    const avTemplate = useSelector(
        (state: RootState) => state.case.templateData[CaseAllocationType.ADDRESS_VERIFICATION_CASE],
    );

    const collectionTemplate = useSelector(
        (state: RootState) => state.case.templateData[CaseAllocationType.COLLECTION_CASE],
      );

    const {isLoggedIn, deviceId, sessionDetails} = user;

    interactionsHandler()
    const dispatch = useAppDispatch();
    NetworkStatusService.listenForOnline(dispatch);

    // Firestore listener hook
      useFirestoreUpdates();
      
    if (!deviceId) {
        getUniqueId().then(id => dispatch(setDeviceId(id)));
    }
    // for setting user token in global.ts for api calling's
    setGlobalUserData(sessionDetails?.sessionToken, deviceId, user?.user?.referenceId);
  
    const getScreenFocusListenerObj = ({route}: {route: RouteProp<GenericType>}) => ({
        focus: () => {
            crashlytics().log(JSON.stringify(route));
        }
    });
  
    registerNavigateAndDispatch(dispatch);
  
    // useEffect(() => {
    //     (async () => {
    //         const loanIdToValueStored = await getLoanIdToValueFromLocal();
    //         if (loanIdToValueStored) {
    //             dispatch(setLoanIdToValue(loanIdToValueStored));
    //         }
    //     })();
    // }, []);

    return (
        <Stack.Navigator>
            {isLoggedIn ? (
                <>
                    <Stack.Screen
                        name="Home"
                        component={AllCasesMain}
                        options={{
                            header: () => null,
                            animation: 'slide_from_right',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name="Profile"
                        component={Profile}
                        options={{
                            header: () => null,
                            animation: 'slide_from_right',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name="caseDetail"
                        component={CaseDetails}
                        options={{
                            header: () => null,
                            animationDuration: ANIMATION_DURATION,
                            animation: 'none',
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name={PageRouteEnum.COLLECTION_CASE_DETAIL}
                        component={CollectionCaseDetails}
                        options={{
                            header: () => null,
                            animationDuration: ANIMATION_DURATION,
                            animation: 'none',
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name={PageRouteEnum.PAYMENTS}
                        component={RegisterPayments}
                        options={{
                            header: () => null,
                            animationDuration: ANIMATION_DURATION,
                            animation: 'none',
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name={PageRouteEnum.ADDRESS_GEO}
                        component={AddressGeolocation}
                        options={{
                            header: () => null,
                            animationDuration: ANIMATION_DURATION,
                            animation: 'none',
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name={PageRouteEnum.NEW_ADDRESS}
                        component={NewAddressContainer}
                        options={{
                            header: () => null,
                            animationDuration: ANIMATION_DURATION,
                            animation: 'none',
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name={PageRouteEnum.PAST_FEEDBACK_DETAIL}
                        component={FeedbackDetailContainer}
                        options={{
                            header: () => null,
                            animationDuration: ANIMATION_DURATION,
                            animation: 'none',
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    {_map(avTemplate?.widget, key => (
                        <Stack.Screen
                            key={getTemplateRoute(
                                key,
                                CaseAllocationType.ADDRESS_VERIFICATION_CASE,
                            )}
                            name={getTemplateRoute(
                                key,
                                CaseAllocationType.ADDRESS_VERIFICATION_CASE,
                            )}
                            component={Widget}
                            options={{
                                header: () => null,
                                animation: 'slide_from_right',
                                animationDuration: ANIMATION_DURATION,
                            }}
                            listeners={getScreenFocusListenerObj}
                        />
                    ))}
                    {_map(collectionTemplate?.widget, key => (
                        <Stack.Screen
                            key={getTemplateRoute(
                                key,
                                CaseAllocationType.COLLECTION_CASE,
                            )}
                            name={getTemplateRoute(
                                key,
                                CaseAllocationType.COLLECTION_CASE,
                            )}
                            component={Widget}
                            options={{
                                header: () => null,
                                animation: 'slide_from_right',
                                animationDuration: ANIMATION_DURATION,
                            }}
                            listeners={getScreenFocusListenerObj}
                        />
                    ))}
                    <Stack.Screen
                        name="TodoList"
                        component={TodoList}
                        options={{
                            header: () => null,
                            animation: 'slide_from_bottom',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name="CompletedCases"
                        component={CompletedCase}
                        options={{
                            header: () => null,
                            animation: 'slide_from_right',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name="EmiSchedule"
                        component={EmiSchedule}
                        options={{
                            header: () => null,
                            animation: 'slide_from_right',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                </>
            ) : (
                <>
                    <Stack.Screen
                        name="Login"
                        component={Login}
                        options={{
                            header: () => null,
                            animation: 'slide_from_right',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                    <Stack.Screen
                        name="OTP"
                        component={OtpInput}
                        options={{
                            header: () => null,
                            animation: 'slide_from_right',
                            animationDuration: ANIMATION_DURATION,
                        }}
                        listeners={getScreenFocusListenerObj}
                    />
                </>
            )}
        </Stack.Navigator>
    );
};

export default ProtectedRouter;
