import { create } from 'zustand';
import { createToken, verifyToken } from '@/lib/auth';

export type PageName =
  | 'login'
  | 'dashboard'
  | 'santri'
  | 'hafalan'
  | 'ngaji'
  | 'jilid'
  | 'ortu-dashboard'
  | 'laporan'
  | 'kepsek-dashboard'
  | 'kepsek-guru'
  | 'kepsek-santri';

interface User {
  id: string;
  nama: string;
  email?: string;
  kelas?: string;
  kelompokBacaan?: string;
  guruNama?: string;
  role: 'guru' | 'ortu' | 'kepsek';
}

interface AppState {
  user: User | null;
  token: string | null;
  isLoginTab: 'guru' | 'ortu' | 'kepsek';
  currentPage: PageName;
  selectedSantriId: string | null;

  setLoginTab: (tab: 'guru' | 'ortu' | 'kepsek') => void;
  login: (user: User) => void;
  logout: () => void;
  restoreSession: () => void;
  navigate: (page: PageName) => void;
  selectSantri: (id: string | null) => void;
}

const TOKEN_KEY = 'ummi_token';

function getHomePage(role: string): PageName {
  if (role === 'kepsek') return 'kepsek-dashboard';
  if (role === 'guru') return 'dashboard';
  return 'ortu-dashboard';
}

export const useAppStore = create<AppState>((set) => ({
  user: null,
  token: null,
  isLoginTab: 'guru',
  currentPage: 'login',
  selectedSantriId: null,

  setLoginTab: (tab) => set({ isLoginTab: tab }),

  login: (user) => {
    createToken(user as unknown as Record<string, unknown>).then((token) => {
      localStorage.setItem(TOKEN_KEY, token);
      set({
        user,
        token,
        currentPage: getHomePage(user.role),
      });
    });
  },

  logout: () => {
    if (typeof window !== 'undefined') {
      localStorage.removeItem(TOKEN_KEY);
    }
    set({ user: null, token: null, currentPage: 'login', selectedSantriId: null });
  },

  restoreSession: () => {
    if (typeof window === 'undefined') return;
    const token = localStorage.getItem(TOKEN_KEY);
    if (!token) return;

    verifyToken(token).then((payload) => {
      if (!payload) {
        localStorage.removeItem(TOKEN_KEY);
        return;
      }
      set({
        user: payload as unknown as User,
        token,
        currentPage: getHomePage(payload.role as string),
      });
    });
  },

  navigate: (page) => set({ currentPage: page }),
  selectSantri: (id) => set({ selectedSantriId: id }),
}));