import { create } from 'zustand';
import type { NavTab } from '@/types';

interface ToastData {
  type: 'success' | 'error' | 'info';
  message: string;
}

interface UIState {
  activeTab: NavTab;
  activeScreen: string;
  previousScreen: string | null;
  toast: ToastData | null;
  isOnline: boolean;
  showSkeleton: boolean;
  headerCompact: boolean;
  bottomSheet: { isOpen: boolean; title: string; content: string; data?: unknown } | null;
  navDirection: 'push' | 'pop' | 'none';
  setActiveTab: (tab: NavTab) => void;
  navigateTo: (screen: string, data?: unknown) => void;
  goBack: () => void;
  showToast: (toast: ToastData) => void;
  clearToast: () => void;
  setBottomSheet: (sheet: UIState['bottomSheet']) => void;
  setHeaderCompact: (compact: boolean) => void;
  setOnline: (online: boolean) => void;
}

export const useUIStore = create<UIState>((set, get) => ({
  activeTab: 'dashboard',
  activeScreen: 'dashboard',
  previousScreen: null,
  toast: null,
  isOnline: true,
  showSkeleton: false,
  headerCompact: false,
  bottomSheet: null,
  navDirection: 'none',

  setActiveTab: (tab) => {
    const screenMap: Record<NavTab, string> = {
      dashboard: 'dashboard',
      students: 'students',
      timing: 'timing',
      attendance: 'attendance',
      reports: 'reports',
      more: 'more',
    };
    set({ activeTab: tab, activeScreen: screenMap[tab], previousScreen: null, navDirection: 'none' });
  },

  navigateTo: (screen, data) => {
    const current = get().activeScreen;
    set({ previousScreen: current, activeScreen: screen, navDirection: 'push', bottomSheet: null });
  },

  goBack: () => {
    const prev = get().previousScreen;
    if (prev) {
      set({ activeScreen: prev, previousScreen: null, navDirection: 'pop', bottomSheet: null });
    }
  },

  showToast: (toast) => {
    set({ toast });
    setTimeout(() => set({ toast: null }), 3000);
  },

  clearToast: () => set({ toast: null }),

  setBottomSheet: (sheet) => set({ bottomSheet: sheet }),
  setHeaderCompact: (compact) => set({ headerCompact: compact }),
  setOnline: (online) => set({ isOnline: online }),
}));
