import { create } from 'zustand'

export type AppView = 'login' | 'dashboard' | 'clients' | 'plans' | 'billing' | 'invoices'
  | 'payments' | 'tickets' | 'resellers' | 'areas' | 'onu' | 'olt'
  | 'reports' | 'settings' | 'logs' | 'whatsapp' | 'user-portal'

export type ClientTabType = 'active' | 'expired' | 'suspended' | 'closed' | 'pending' | 'online' | 'offline' | 'new' | 'high-usage' | 'due-payment'

type User = {
  id: string; email: string; name: string; phone: string; role: string;
  status: string; areaId: string | null; connectionType: string;
}

interface AppState {
  // Auth
  currentUser: User | null
  isAuthenticated: boolean
  token: string | null

  // Navigation
  currentView: AppView
  sidebarOpen: boolean

  // Client management
  clientTab: ClientTabType
  selectedClientIds: string[]

  // Theme
  theme: 'light' | 'dark'

  // Actions
  login: (user: User, token: string) => void
  logout: () => void
  setCurrentView: (view: AppView) => void
  setSidebarOpen: (open: boolean) => void
  setClientTab: (tab: ClientTabType) => void
  setSelectedClientIds: (ids: string[]) => void
  toggleClientSelection: (id: string) => void
  selectAllClients: (ids: string[]) => void
  clearClientSelection: () => void
  setTheme: (theme: 'light' | 'dark') => void
  toggleTheme: () => void
}

export const useAppStore = create<AppState>((set) => ({
  currentUser: null,
  isAuthenticated: false,
  token: null,
  currentView: 'login',
  sidebarOpen: true,
  clientTab: 'active',
  selectedClientIds: [],
  theme: 'light',

  login: (user, token) => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('isp_token', token)
      localStorage.setItem('isp_user', JSON.stringify(user))
    }
    set({ currentUser: user, isAuthenticated: true, token, currentView: 'dashboard' })
  },
  logout: () => {
    if (typeof window !== 'undefined') {
      localStorage.removeItem('isp_token')
      localStorage.removeItem('isp_user')
    }
    set({ currentUser: null, isAuthenticated: false, token: null, currentView: 'login' })
  },
  setCurrentView: (view) => set({ currentView: view }),
  setSidebarOpen: (open) => set({ sidebarOpen: open }),
  setClientTab: (tab) => set({ clientTab: tab }),
  setSelectedClientIds: (ids) => set({ selectedClientIds: ids }),
  toggleClientSelection: (id) =>
    set((state) => ({
      selectedClientIds: state.selectedClientIds.includes(id)
        ? state.selectedClientIds.filter((cid) => cid !== id)
        : [...state.selectedClientIds, id],
    })),
  selectAllClients: (ids) => set({ selectedClientIds: ids }),
  clearClientSelection: () => set({ selectedClientIds: [] }),
  setTheme: (theme) => {
    if (typeof window !== 'undefined') {
      localStorage.setItem('isp_theme', theme)
      document.documentElement.classList.toggle('dark', theme === 'dark')
    }
    set({ theme })
  },
  toggleTheme: () =>
    set((state) => {
      const newTheme = state.theme === 'light' ? 'dark' : 'light'
      if (typeof window !== 'undefined') {
        localStorage.setItem('isp_theme', newTheme)
        document.documentElement.classList.toggle('dark', newTheme === 'dark')
      }
      return { theme: newTheme }
    }),
}))

// Initialize from localStorage
if (typeof window !== 'undefined') {
  const token = localStorage.getItem('isp_token')
  const userStr = localStorage.getItem('isp_user')
  const theme = localStorage.getItem('isp_theme') as 'light' | 'dark' | null

  if (token && userStr) {
    try {
      const user = JSON.parse(userStr)
      useAppStore.setState({ currentUser: user, isAuthenticated: true, token, currentView: 'dashboard' })
    } catch { /* ignore */ }
  }
  if (theme) {
    useAppStore.setState({ theme })
    document.documentElement.classList.toggle('dark', theme === 'dark')
  }
}
