import { create } from 'zustand'
import { v4 as uuidv4 } from 'uuid'
import { initializeObjectsState } from './objects'
import { initializeMapState } from './map'

export type Mode = 'edit' | 'view'
export type ColorScheme = 'light' | 'dark' | 'auto'

export interface MapTabState {
    year: number | null
    region: number | null
    district: number | null
}

export interface AppState {
    colorScheme: ColorScheme
    mapTab: Record<string, MapTabState>
    tabOrder: string[]             // 👈 defines tab order
    currentTab: string | null
}

export const useAppStore = create<AppState>(() => {
    const firstId = uuidv4()

    initializeObjectsState(firstId, null, null, null, null)
    initializeMapState(firstId)

    return {
        colorScheme: "auto",
        currentTab: firstId,
        mapTab: {
            [firstId]: { year: null, region: null, district: null },
        },
        tabOrder: [firstId],
    }
})

// getters/setters
export const getColorScheme = () => useAppStore.getState().colorScheme

export const setColorScheme = (colorScheme: ColorScheme) => {
    useAppStore.setState(() => ({ colorScheme }))
    localStorage.setItem('colorScheme', colorScheme.toString())
}

export const getCurrentTab = () => useAppStore.getState().currentTab
export const setCurrentTab = (id: string | null) => useAppStore.setState(() => ({ currentTab: id }))

export const setMapTabYear = (id: string, year: number | null) =>
    useAppStore.setState((state) => ({
        mapTab: {
            ...state.mapTab,
            [id]: { ...state.mapTab[id], year },
        },
    }))

export const deleteMapTab = (id: string) =>
    useAppStore.setState((state) => {
        const { [id]: _, ...remainingTabs } = state.mapTab
        const newOrder = state.tabOrder.filter((tid) => tid !== id)

        return {
            mapTab: remainingTabs,
            tabOrder: newOrder,
            currentTab: newOrder.length > 0 ? newOrder[newOrder.length - 1] : null,
        }
    })

export const addMapTab = () => {
    const id = uuidv4()
    initializeObjectsState(id, null, null, null, null)
    initializeMapState(id)

    useAppStore.setState((state) => ({
        mapTab: {
            ...state.mapTab,
            [id]: { year: null, region: null, district: null },
        },
        tabOrder: [...state.tabOrder, id],
        currentTab: id,
    }))

    return id
}

export const reorderTabs = (from: number, to: number) =>
    useAppStore.setState((state) => {
        const newOrder = Array.from(state.tabOrder)
        const [moved] = newOrder.splice(from, 1)
        newOrder.splice(to, 0, moved)
        return { tabOrder: newOrder }
    })
