import { ref } from 'vue'

export function useDataTableActions(gridApi, rowData) {
  const showDetailsDialog = ref(false)
  const showDeleteDialog = ref(false)
  const selectedRowData = ref(null)
  const deleteRowData = ref(null)

  const getRowDataByIndex = (rowIndex) => {
    if (!gridApi.value) {
      console.error('Grid API not available')
      return null
    }

    try {
      const node = gridApi.value.getDisplayedRowAtIndex(rowIndex)
      if (node && node.data) {
        return node.data
      }

      if (rowData.value && rowData.value[rowIndex]) {
        return rowData.value[rowIndex]
      }

      console.error('Row data not found for index:', rowIndex)
      return null
    } catch (error) {
      console.error('Error getting row data:', error)
      return null
    }
  }

  const showDetails = (rowIndex, nodeId) => {
    console.log('Show details called with:', { rowIndex, nodeId })
    
    const rowData = getRowDataByIndex(rowIndex)
    if (rowData) {
      selectedRowData.value = { ...rowData }
      showDetailsDialog.value = true
      console.log('Selected row data:', selectedRowData.value)
    } else {
      console.error('Failed to get row data for details')
    }
  }

  const editRow = (rowIndex, nodeId) => {
    console.log('Edit row called with:', { rowIndex, nodeId })
    
    if (!gridApi.value) {
      console.error('Grid API not available for editing')
      return
    }

    try {
      gridApi.value.startEditingCell({
        rowIndex: rowIndex,
        colKey: 'fullName' 
      })
      console.log('Started inline editing for row:', rowIndex)
    } catch (error) {
      console.error('Error starting inline edit:', error)
    }
  }

  const deleteRow = (rowIndex, nodeId) => {
    console.log('Delete row called with:', { rowIndex, nodeId })
    
    const rowData = getRowDataByIndex(rowIndex)
    if (rowData) {
      deleteRowData.value = { ...rowData }
      showDeleteDialog.value = true
      console.log('Delete row data:', deleteRowData.value)
    } else {
      console.error('Failed to get row data for delete')
    }
  }

  const confirmDelete = () => {
    if (deleteRowData.value && gridApi.value) {
      try {
        const indexToDelete = rowData.value.findIndex(item => {
          return (
            (item.id && item.id === deleteRowData.value.id) ||
            (item.email && item.email === deleteRowData.value.email) ||
            (item.fullName === deleteRowData.value.fullName && 
             item.salary === deleteRowData.value.salary)
          )
        })
        
        if (indexToDelete !== -1) {
          rowData.value.splice(indexToDelete, 1)
        
          gridApi.value.applyTransaction({
            remove: [deleteRowData.value]
          })
          
          console.log('Row deleted successfully')
        } else {
          console.error('Row not found for deletion')
        }
      } catch (error) {
        console.error('Error deleting row:', error)
      }
    }
    
    showDeleteDialog.value = false
    deleteRowData.value = null
  }

  const cancelDelete = () => {
    showDeleteDialog.value = false
    deleteRowData.value = null
  }

  const saveUser = (editedData) => {
    if (!editedData || !gridApi.value) return

    try {
      const indexToUpdate = rowData.value.findIndex(item => {
        return (
          (item.id && item.id === editedData.id) ||
          (item.email && item.email === selectedRowData.value.email) ||
          (item.fullName === selectedRowData.value.fullName)
        )
      })

      if (indexToUpdate !== -1) {
        rowData.value[indexToUpdate] = { ...editedData }
        
        const node = gridApi.value.getRowNode(indexToUpdate)
        if (node) {
          node.setData(editedData)
        }
        
        console.log('User updated successfully:', editedData)
      } else {
        console.error('User not found for update')
      }
    } catch (error) {
      console.error('Error updating user:', error)
    }

    showDetailsDialog.value = false
    selectedRowData.value = null
  }

  const exportToCSV = () => {
    if (gridApi.value) {
      gridApi.value.exportDataAsCsv({
        fileName: `datatable-export-${new Date().toISOString().split('T')[0]}.csv`,
        columnSeparator: ',',
        suppressQuotes: false,
        onlySelected: false,
        skipGroups: true,
        skipHeader: false,
        skipFooters: true,
        skipPinnedTop: true,
        skipPinnedBottom: true,
        allColumns: false,
        onlySelectedAllPages: false
      })
    }
  }

  const exportToExcel = () => {
    if (gridApi.value) {
      gridApi.value.exportDataAsExcel({
        fileName: `datatable-export-${new Date().toISOString().split('T')[0]}.xlsx`,
        sheetName: 'Data Export',
        onlySelected: false,
        skipGroups: true,
        skipHeader: false,
        skipFooters: true,
        skipPinnedTop: true,
        skipPinnedBottom: true,
        allColumns: false,
        onlySelectedAllPages: false
      })
    }
  }

  const setupGlobalHandlers = () => {
    window.handleShowDetails = showDetails
    window.handleEditRow = editRow
    window.handleDeleteRow = deleteRow
  }

  const cleanupGlobalHandlers = () => {
    delete window.handleShowDetails
    delete window.handleEditRow
    delete window.handleDeleteRow
  }

  return {
    showDetailsDialog,
    showDeleteDialog,
    selectedRowData,
    deleteRowData,
    showDetails,
    editRow,
    deleteRow,
    confirmDelete,
    cancelDelete,
    saveUser,
    exportToCSV,
    exportToExcel,
    setupGlobalHandlers,
    cleanupGlobalHandlers
  }
}