import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import router from '../router'

export const useAuthStore = defineStore('auth', () => {
  // State
  const token = ref(localStorage.getItem('token') || '')
  const isAdmin = ref(localStorage.getItem('is_admin') === 'true')
  const userEmail = ref(localStorage.getItem('user_email') || '')
  const userRole = ref(localStorage.getItem('user_role') || '')
  const userProfile = ref(null) // Full user profile from /users/me
  const activeOrgId = ref(localStorage.getItem('active_org_id') || null) // Active organization ID
  
  // Getters
  const isLoggedIn = computed(() => !!token.value)
  const isTester = computed(() => userEmail.value === 'tester_pro@profibot.hu' || userRole.value === 'tester')
  const displayName = computed(() => {
    if (isTester.value) return 'TESTER PRO'
    if (isAdmin.value) return 'ADMIN'
    return 'USER'
  })
  
  // Actions
  const login = async (email, password) => {
    console.log('AuthStore: Real API login attempt for', email)
    
    try {
      // Prepare URL-encoded form data for OAuth2 password grant
      // FastAPI's OAuth2PasswordRequestForm expects application/x-www-form-urlencoded
      const params = new URLSearchParams()
      params.append('username', email)
      params.append('password', password)
      
      // Call real backend API
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu';
      const response = await fetch(`${apiBaseUrl}/auth/login`, {
        method: 'POST',
        body: params,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        const errorText = await response.text()
        console.error('AuthStore: Login API error', response.status, errorText)
        throw new Error(`Login failed: ${response.status} ${response.statusText}`)
      }
      
      const data = await response.json()
      console.log('AuthStore: Login API response', data)
      
      // Extract token and user info
      const accessToken = data.access_token
      const refreshToken = data.refresh_token
      const tokenType = data.token_type
      const isActive = data.is_active
      
      // We need to decode the JWT token to get user role and info
      // For now, we'll make a separate API call to get user info
      // Or we can parse the JWT token (simple base64 decode)
      let roleValue = 'user'
      let adminFlag = false
      
      try {
        // Decode JWT token to get payload
        const tokenParts = accessToken.split('.')
        if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]))
          roleValue = payload.role || 'user'
          adminFlag = roleValue === 'admin' || roleValue === 'superadmin'
          console.log('AuthStore: Decoded JWT payload', payload)
        }
      } catch (decodeError) {
        console.warn('AuthStore: Could not decode JWT token', decodeError)
        // Fallback: Make API call to get user info
        // For now, we'll use a default role
      }
      
      // Save to localStorage
      localStorage.setItem('token', accessToken)
      localStorage.setItem('refresh_token', refreshToken)
      localStorage.setItem('is_admin', adminFlag.toString())
      localStorage.setItem('user_email', email)
      localStorage.setItem('user_role', roleValue)
      
      // Update store state
      token.value = accessToken
      isAdmin.value = adminFlag
      userEmail.value = email
      userRole.value = roleValue
      
      console.log('AuthStore: State updated, redirecting to /profile-select')
      
      // Redirect to profile-select (as per router logic)
      try {
        await router.push('/profile-select')
        console.log('AuthStore: Redirect successful')
      } catch (error) {
        console.error('AuthStore: Router redirect failed:', error)
        throw error
      }
      
      return { success: true, token: accessToken, isAdmin: adminFlag, role: roleValue }
      
    } catch (error) {
      console.error('AuthStore: Login failed', error)
      throw error // Re-throw the error instead of falling back to mock
    }
  }
  
  const logout = () => {
    // Clear localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('is_admin')
    localStorage.removeItem('user_email')
    localStorage.removeItem('user_role')
    localStorage.removeItem('ui_mode') // Also clear UI mode on logout
    localStorage.removeItem('active_org_id') // Clear active organization ID
    
    // Reset store state
    token.value = ''
    isAdmin.value = false
    userEmail.value = ''
    userRole.value = ''
    userProfile.value = null
    activeOrgId.value = null
    
    // Redirect to login
    router.push('/login')
  }
  
  const fetchUserProfile = async () => {
    if (!token.value) {
      throw new Error('Not authenticated')
    }
    
    try {
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu';
      const response = await fetch(`${apiBaseUrl}/users/me`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token.value}`,
          'Accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`Failed to fetch user profile: ${response.status} ${response.statusText}`)
      }
      
      const data = await response.json()
      console.log('AuthStore: Fetched user profile', data)
      
      // Update user profile state
      userProfile.value = data
      
      // Also update email and role from profile if available
      if (data.email && !userEmail.value) {
        userEmail.value = data.email
        localStorage.setItem('user_email', data.email)
      }
      
      if (data.role && !userRole.value) {
        userRole.value = data.role
        localStorage.setItem('user_role', data.role)
        isAdmin.value = data.role === 'admin' || data.role === 'superadmin'
        localStorage.setItem('is_admin', isAdmin.value.toString())
      }
      
      // Store active organization ID if available
      if (data.active_organization_id !== undefined) {
        activeOrgId.value = data.active_organization_id
        localStorage.setItem('active_org_id', data.active_organization_id)
        console.log('AuthStore: Set active organization ID:', data.active_organization_id)
      } else if (data.scope_id) {
        // Fallback to scope_id if active_organization_id is not provided
        activeOrgId.value = data.scope_id
        localStorage.setItem('active_org_id', data.scope_id)
        console.log('AuthStore: Set active organization ID from scope_id:', data.scope_id)
      }
      
      return data
    } catch (err) {
      console.error('AuthStore: Error fetching user profile', err)
      throw err
    }
  }
  
  // Update active organization
  const updateActiveOrganization = async (organizationId) => {
    if (!token.value) {
      throw new Error('Not authenticated')
    }
    
    try {
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu';
      const response = await fetch(`${apiBaseUrl}/users/me/active-organization`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token.value}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          organization_id: organizationId
        })
      })
      
      if (!response.ok) {
        throw new Error(`Failed to update active organization: ${response.status} ${response.statusText}`)
      }
      
      const data = await response.json()
      console.log('AuthStore: Updated active organization', data)
      
      // Check if response contains new JWT token (backend now returns {user: {...}, access_token: "...", token_type: "bearer"})
      if (data.access_token) {
        console.log('AuthStore: Received new access token from organization switch')
        
        // Update token in localStorage and store state
        localStorage.setItem('token', data.access_token)
        token.value = data.access_token
        
        // Decode new token to update role if needed
        try {
          const tokenParts = data.access_token.split('.')
          if (tokenParts.length === 3) {
            const payload = JSON.parse(atob(tokenParts[1]))
            const roleValue = payload.role || 'user'
            const adminFlag = roleValue === 'admin' || roleValue === 'superadmin'
            
            localStorage.setItem('user_role', roleValue)
            localStorage.setItem('is_admin', adminFlag.toString())
            
            userRole.value = roleValue
            isAdmin.value = adminFlag
            console.log('AuthStore: Updated role from new token:', roleValue)
          }
        } catch (decodeError) {
          console.warn('AuthStore: Could not decode new JWT token', decodeError)
        }
      }
      
      // Update local state
      activeOrgId.value = organizationId
      localStorage.setItem('active_org_id', organizationId || '')
      
      // Also update user profile to reflect changes
      await fetchUserProfile()
      
      return data
    } catch (err) {
      console.error('AuthStore: Error updating active organization', err)
      throw err
    }
  }
  
  const checkAuth = () => {
    // Sync with localStorage on page load
    const storedToken = localStorage.getItem('token') || ''
    const storedEmail = localStorage.getItem('user_email') || ''
    const storedRole = localStorage.getItem('user_role') || ''
    
    // Try to decode JWT token to get role if not stored
    let decodedRole = storedRole
    let decodedIsAdmin = storedRole === 'admin' || storedRole === 'superadmin'
    
    if (storedToken && !storedRole) {
      try {
        // Decode JWT token to get payload
        const tokenParts = storedToken.split('.')
        if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]))
          decodedRole = payload.role || 'user'
          decodedIsAdmin = decodedRole === 'admin' || decodedRole === 'superadmin'
          console.log('AuthStore: Decoded JWT on checkAuth', payload)
          
          // Update localStorage with decoded role
          localStorage.setItem('user_role', decodedRole)
          localStorage.setItem('is_admin', decodedIsAdmin.toString())
        }
      } catch (decodeError) {
        console.warn('AuthStore: Could not decode JWT token on checkAuth', decodeError)
      }
    } else if (storedToken && storedRole) {
      // Use stored role
      decodedIsAdmin = storedRole === 'admin' || storedRole === 'superadmin'
    }
    
    token.value = storedToken
    isAdmin.value = decodedIsAdmin
    userEmail.value = storedEmail
    userRole.value = decodedRole || 'user'
  }
  
  // Initialize on store creation
  checkAuth()
  
  return {
    // State
    token,
    isAdmin,
    userEmail,
    userRole,
    userProfile,
    activeOrgId,
    
    // Getters
    isLoggedIn,
    isTester,
    displayName,
    
    // Actions
    login,
    logout,
    checkAuth,
    fetchUserProfile,
    updateActiveOrganization
  }
})