import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { safeStorage } from '../utils/safe-storage';

export type MobileScreen = 'Dashboard' | 'Vehicles' | 'Log Fuel' | 'Maintenance' | 'Stations' | 'Documents' | 'Settings' | 'Security' | 'Subscription' | 'AdminUsers' | 'AdminCatalog' | 'AdminCommunityStations' | 'AdminEmailTemplates' | 'AdminBackup' | 'AdminLogs';
export type VehicleSubScreen = 'list' | 'detail' | 'add' | 'edit';

interface NavigationHistory {
  screen: MobileScreen;
  vehicleSubScreen?: VehicleSubScreen;
  selectedVehicleId?: string | null;
  timestamp: number;
  metadata?: Record<string, any>;
}

interface FormState {
  data: Record<string, any>;
  timestamp: number;
  isDirty: boolean;
}

interface NavigationState {
  // Current navigation state
  activeScreen: MobileScreen;
  vehicleSubScreen: VehicleSubScreen;
  selectedVehicleId: string | null;

  // Navigation history for back button
  navigationHistory: NavigationHistory[];

  // Form state preservation
  formStates: Record<string, FormState>;

  // Loading and error states
  isNavigating: boolean;
  navigationError: string | null;

  // Actions
  navigateToScreen: (screen: MobileScreen, metadata?: Record<string, any>) => void;
  navigateToVehicleSubScreen: (subScreen: VehicleSubScreen, vehicleId?: string, metadata?: Record<string, any>) => void;
  goBack: () => boolean;
  canGoBack: () => boolean;
  saveFormState: (formId: string, data: any, isDirty?: boolean) => void;
  restoreFormState: (formId: string) => FormState | null;
  clearFormState: (formId: string) => void;
  clearAllFormStates: () => void;
  setNavigationError: (error: string | null) => void;
}

export const useNavigationStore = create<NavigationState>()(
  persist(
    (set, get) => ({
      // Initial state
      activeScreen: 'Dashboard',
      vehicleSubScreen: 'list',
      selectedVehicleId: null,
      navigationHistory: [],
      formStates: {},
      isNavigating: false,
      navigationError: null,

      // Navigation actions
      navigateToScreen: (screen, metadata = {}) => {
        const currentState = get();

        // Skip navigation if already on the same screen
        if (currentState.activeScreen === screen && !currentState.isNavigating) {
          return;
        }

        try {
          const historyEntry: NavigationHistory = {
            screen: currentState.activeScreen,
            vehicleSubScreen: currentState.vehicleSubScreen,
            selectedVehicleId: currentState.selectedVehicleId,
            timestamp: Date.now(),
            metadata,
          };

          // Update state atomically to prevent blank screens
          set({
            activeScreen: screen,
            vehicleSubScreen: screen === 'Vehicles' ? currentState.vehicleSubScreen : 'list',
            selectedVehicleId: screen === 'Vehicles' ? currentState.selectedVehicleId : null,
            navigationHistory: [...currentState.navigationHistory, historyEntry].slice(-10),
            isNavigating: false,
            navigationError: null,
          });
        } catch (error) {
          set({
            navigationError: error instanceof Error ? error.message : 'Navigation failed',
            isNavigating: false
          });
        }
      },

      navigateToVehicleSubScreen: (subScreen, vehicleId, metadata = {}) => {
        const currentState = get();

        set({ isNavigating: true, navigationError: null });

        try {
          const historyEntry: NavigationHistory = {
            screen: currentState.activeScreen,
            vehicleSubScreen: currentState.vehicleSubScreen,
            selectedVehicleId: currentState.selectedVehicleId,
            timestamp: Date.now(),
            metadata,
          };

          set({
            vehicleSubScreen: subScreen,
            selectedVehicleId: vehicleId !== null ? vehicleId : currentState.selectedVehicleId,
            navigationHistory: [...currentState.navigationHistory, historyEntry].slice(-10),
            isNavigating: false,
          });
        } catch (error) {
          set({
            navigationError: error instanceof Error ? error.message : 'Navigation failed',
            isNavigating: false
          });
        }
      },

      goBack: () => {
        const currentState = get();
        const lastEntry = currentState.navigationHistory[currentState.navigationHistory.length - 1];

        if (lastEntry) {
          set({
            activeScreen: lastEntry.screen,
            vehicleSubScreen: lastEntry.vehicleSubScreen || 'list',
            selectedVehicleId: lastEntry.selectedVehicleId,
            navigationHistory: currentState.navigationHistory.slice(0, -1),
            isNavigating: false,
            navigationError: null,
          });
          return true;
        }
        return false;
      },

      canGoBack: () => {
        return get().navigationHistory.length > 0;
      },

      // Form state management
      saveFormState: (formId, data, isDirty = true) => {
        const currentState = get();
        const formState: FormState = {
          data,
          timestamp: Date.now(),
          isDirty,
        };

        set({
          formStates: {
            ...currentState.formStates,
            [formId]: formState,
          },
        });
      },

      restoreFormState: (formId) => {
        const state = get().formStates[formId];
        const maxAge = 2 * 60 * 60 * 1000; // 2 hours

        if (state && Date.now() - state.timestamp < maxAge) {
          return state;
        }

        // Clean up old state
        if (state) {
          get().clearFormState(formId);
        }

        return null;
      },

      clearFormState: (formId) => {
        const currentState = get();
        const newFormStates = { ...currentState.formStates };
        delete newFormStates[formId];
        set({ formStates: newFormStates });
      },

      clearAllFormStates: () => {
        set({ formStates: {} });
      },

      setNavigationError: (error) => {
        set({ navigationError: error });
      },
    }),
    {
      name: 'motovaultpro-mobile-navigation',
      storage: createJSONStorage(() => safeStorage),
      partialize: (state) => ({
        activeScreen: state.activeScreen,
        vehicleSubScreen: state.vehicleSubScreen,
        selectedVehicleId: state.selectedVehicleId,
        formStates: state.formStates,
      }),
      onRehydrateStorage: () => (state) => {
        if (state) {
          console.log('[Navigation] State rehydrated successfully');
        } else {
          console.warn('[Navigation] State rehydration failed, using defaults');
        }
      },
    }
  )
);
