import {
    addFranchiseesToGroups as addFranchiseesToGroupsAPI,
    assignGroupsToFranchisee as assignGroupsToFranchiseeAPI,
    createFranchiseeGroup,
    deleteFranchiseeGroup,
    fetchFranchiseeGroups,
    updateFranchiseeGroup
} from '@/api/franchiseeGroup'
import {
    extractErrorMessage,
    showToast,
} from '@/composables/useStoreHelpers'
import { createCacheManager } from '@/utils/cacheManager'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

const cacheManager = createCacheManager('franchisee-groups', 10 * 60 * 1000) // 10 minutes

export const useFranchiseeGroupStore = defineStore('franchiseeGroup', () => {
  // State
  const groups = ref([])
  const total = ref(0)
  const loading = ref(false)
  const saving = ref(false)
  const deleting = ref(false)

  // Actions
  const fetchGroups = async (params = {}) => {
    const cacheKey = cacheManager.generateKey(params)
    
    // Check cache first
    const cachedData = cacheManager.load(cacheKey)
    if (cachedData) {
      groups.value = cachedData.groups || []
      total.value = cachedData.total || 0
      return { success: true, data: cachedData }
    }

    loading.value = true
    try {
      const response = await fetchFranchiseeGroups(params)
      
      // Handle different response structures
      if (response.data?.data && Array.isArray(response.data.data.data)) {
        groups.value = response.data.data.data
        total.value = response.data.data.total
      } else if (response.data?.data && Array.isArray(response.data.data)) {
        groups.value = response.data.data
        total.value = response.data.total || response.data.data.length
      } else if (Array.isArray(response.data)) {
        groups.value = response.data
        total.value = response.data.length
      }

      // Save to cache
      cacheManager.save(cacheKey, {
        groups: groups.value,
        total: total.value
      })
      cacheManager.clearExpired()

      return { success: true, data: response.data }
    } catch (error) {
      const errorMsg = extractErrorMessage(error)
      showToast('error', 'Error', errorMsg)
      console.error('Error fetching groups:', error)
      return { success: false, message: errorMsg }
    } finally {
      loading.value = false
    }
  }

  const createGroup = async (groupData) => {
    saving.value = true
    try {
      const response = await createFranchiseeGroup(groupData)
      const newGroup = response.data?.data || response.data
      groups.value.push(newGroup)
      total.value++
      cacheManager.clearAll()
      showToast('success', 'Success', 'Franchisee group created successfully')
      return { success: true, data: newGroup }
    } catch (error) {
      const errorMsg = extractErrorMessage(error)
      showToast('error', 'Error', errorMsg)
      console.error('Error creating group:', error)
      return { success: false, message: errorMsg }
    } finally {
      saving.value = false
    }
  }

  const updateGroup = async (id, groupData) => {
    saving.value = true
    try {
      const response = await updateFranchiseeGroup(id, groupData)
      const updatedGroup = response.data?.data || response.data
      const index = groups.value.findIndex(g => g.id === id)
      if (index !== -1) {
        groups.value[index] = updatedGroup
      }
      cacheManager.clearAll()
      showToast('success', 'Success', 'Franchisee group updated successfully')
      return { success: true, data: updatedGroup }
    } catch (error) {
      const errorMsg = extractErrorMessage(error)
      showToast('error', 'Error', errorMsg)
      console.error('Error updating group:', error)
      return { success: false, message: errorMsg }
    } finally {
      saving.value = false
    }
  }

  const deleteGroup = async (id) => {
    deleting.value = true
    try {
      await deleteFranchiseeGroup(id)
      groups.value = groups.value.filter(g => g.id !== id)
      total.value--
      cacheManager.clearAll()
      showToast('success', 'Deleted', 'Franchisee group deleted successfully')
      return { success: true }
    } catch (error) {
      const errorMsg = extractErrorMessage(error)
      showToast('error', 'Error', errorMsg)
      console.error('Error deleting group:', error)
      return { success: false, message: errorMsg }
    } finally {
      deleting.value = false
    }
  }

  const addFranchiseesToGroups = async (franchiseeIds, groupIds) => {
    saving.value = true
    try {
      const response = await addFranchiseesToGroupsAPI({
        franchisee_ids: franchiseeIds,
        group_ids: groupIds
      })
      cacheManager.clearAll()
      showToast('success', 'Success', response.data?.message || 'Franchisees added to groups successfully')
      return { success: true, data: response.data }
    } catch (error) {
      const errorMsg = extractErrorMessage(error)
      showToast('error', 'Error', errorMsg)
      console.error('Error adding franchisees to groups:', error)
      return { success: false, message: errorMsg }
    } finally {
      saving.value = false
    }
  }

  const assignGroupsToFranchisee = async (franchiseeId, groupIds) => {
    saving.value = true
    try {
      const response = await assignGroupsToFranchiseeAPI(franchiseeId, {
        group_ids: groupIds
      })
      cacheManager.clearAll()
      showToast('success', 'Success', response.data?.message || 'Groups assigned successfully')
      return { success: true, data: response.data }
    } catch (error) {
      const errorMsg = extractErrorMessage(error)
      showToast('error', 'Error', errorMsg)
      console.error('Error assigning groups:', error)
      return { success: false, message: errorMsg }
    } finally {
      saving.value = false
    }
  }

  // Getters
  const groupsCount = computed(() => groups.value.length)

  return {
    groups,
    total,
    loading,
    saving,
    deleting,
    groupsCount,
    fetchGroups,
    createGroup,
    updateGroup,
    deleteGroup,
    addFranchiseesToGroups,
    assignGroupsToFranchisee,
  }
})
