import { defineStore } from 'pinia'
import axios from 'axios'
import { useOPFS } from '../composables/useOPFS'

const opfs = useOPFS()
const CACHE_KEY_USERS = 'cached_users.json'

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [],
    user: null, // Current logged-in user details
    acctType: sessionStorage.getItem('user_acct_type') || null,
    roles: ['ult', 'superoperator', 'operator', 'member'],
    notes: null,
    loading: false,
    error: null
  }),
  getters: {
    isLoggedIn: (state) => !!state.user || (!!state.acctType && state.acctType !== 'public'),
    fullName: (state) => state.user?.fullname || state.user?.name || 'User',
    photoUrl: (state) => {
      const url = state.user?.photourl;
      if (url) return url;
      const name = state.user?.fullname || state.user?.name || 'User';
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=533dea&color=fff&size=128`;
    },
    mobileNumber: (state) => state.user?.mobile || '',
    landline: (state) => state.user?.landline || '',
    email: (state) => state.user?.email || '',
  },
  actions: {
    async fetchUsers() {
      // Keep this for admin user list
      this.loading = true
      this.error = null

      // Load from cache first
      try {
        const cachedUsers = await opfs.loadJSON(CACHE_KEY_USERS)
        if (cachedUsers && Array.isArray(cachedUsers)) {
          this.users = cachedUsers
        }
      } catch (e) {
        console.warn('Failed to load users from cache:', e)
      }

      try {
        const response = await axios.post('/admin/users/list')
        if (response.data && response.data.success) {
          this.users = response.data.users || []
          
          // Save to cache
          await opfs.saveJSON(CACHE_KEY_USERS, this.users)
        }
      } catch (error) {
        console.error('Failed to fetch users:', error)
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async fetchCurrentUser() {
      this.loading = true
      try {
        const response = await axios.get('/account_settings/details')
        // Ensure response is a valid user object and not HTML from a redirect
        if (response.data && typeof response.data === 'object' && !Array.isArray(response.data)) {
          this.user = response.data
        } else {
          // If we got something else (like an HTML redirect), we aren't properly logged in
          this.user = null
          this.acctType = 'public'
          sessionStorage.setItem('user_acct_type', 'public')
        }
        
        const resRole = await axios.get('/get/user/acct-type')
        if (resRole.data && resRole.data.acct_type) {
            this.acctType = resRole.data.acct_type
            sessionStorage.setItem('user_acct_type', this.acctType)
        }
      } catch (error) {
        console.error('Failed to fetch current user:', error)
        if (error.response?.status === 401 || error.response?.status === 419) {
          this.user = null
          this.acctType = 'public'
          sessionStorage.setItem('user_acct_type', 'public')
        }
      } finally {
        this.loading = false
      }
    },

    async fetchUserById(id) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(`/admin/users/${id}`)
        if (response.data && response.data.success) {
          this.user = response.data.user
        }
      } catch (error) {
        console.error('Failed to fetch user:', error)
        this.error = error.message
      } finally {
        this.loading = false
      }
    },

    async createUser(data) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.post('/admin/users/create', data)
        if (response.data && response.data.success) {
          this.users.push(response.data.user)
        }
        return response.data
      } catch (error) {
        console.error('Failed to create user:', error)
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    async updateUser(id, data) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.put(`/admin/users/${id}`, data)
        if (response.data && response.data.success) {
          const index = this.users.findIndex(u => u.id === id)
          if (index !== -1) {
            this.users[index] = response.data.user
          }
        }
        return response.data
      } catch (error) {
        console.error('Failed to update user:', error)
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    async deleteUser(id) {
      this.loading = true
      this.error = null
      try {
        const response = await axios.delete(`/admin/users/${id}`)
        if (response.data && response.data.success) {
          this.users = this.users.filter(u => u.id !== id)
        }
        return response.data
      } catch (error) {
        console.error('Failed to delete user:', error)
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    async enableUser(id) {
      try {
        const response = await axios.post(`/admin/users/${id}/enable`)
        return response.data
      } catch (error) {
        console.error('Failed to enable user:', error)
        throw error
      }
    },

    async disableUser(id) {
      try {
        const response = await axios.post(`/admin/users/${id}/disable`)
        return response.data
      } catch (error) {
        console.error('Failed to disable user:', error)
        throw error
      }
    },

    resetCurrentUser() {
      this.user = null;
      this.acctType = null;
      sessionStorage.removeItem('user_acct_type');
    },

    setNotes(notesData) {
      this.notes = notesData
    },

    clearNotes() {
      this.notes = null
    },

    executeCommand(commandString) {
      try {
        console.log('[Store user.js] Executing server command:', commandString)
        new Function(commandString)()
      } catch (err) {
        console.error('[Store user.js] Failed to execute server command:', err)
      }
    }
  }
})