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 selectedRowNodeId = ref(null)
  const deleteRowNodeId = ref(null)

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

    try {
      let node = null
      if (nodeId != null && gridApi.value.getRowNode) {
        node = gridApi.value.getRowNode(nodeId)
      }
      if (!node) {
        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 rowDataItem = getRowDataByIndex(rowIndex, nodeId)
    if (rowDataItem) {
      selectedRowData.value = { ...rowDataItem }
      selectedRowNodeId.value = nodeId
      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 {
      const columnDefs = typeof gridApi.value.getColumnDefs === 'function' ? gridApi.value.getColumnDefs() : []
      const firstEditableCol = Array.isArray(columnDefs) ? columnDefs.find(col => col && col.editable && col.field && col.field !== 'action') : null

      if (firstEditableCol && typeof gridApi.value.startEditingCell === 'function') {
        gridApi.value.ensureIndexVisible?.(rowIndex)
        gridApi.value.setFocusedCell?.(rowIndex, firstEditableCol.field)
        gridApi.value.startEditingCell({ rowIndex, colKey: firstEditableCol.field })
        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 rowDataItem = getRowDataByIndex(rowIndex, nodeId)
    if (rowDataItem) {
      deleteRowData.value = { ...rowDataItem }
      deleteRowNodeId.value = nodeId
      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 {
        // Prefer removing via grid transaction using the exact object
        gridApi.value.applyTransaction({ remove: [deleteRowData.value] })

        // Also sync our local rowData list. Try by id first, else fallback to object equality
        let indexToDelete = -1
        if (deleteRowData.value.id != null) {
          indexToDelete = rowData.value.findIndex(item => item && item.id === deleteRowData.value.id)
        }
        if (indexToDelete === -1) {
          indexToDelete = rowData.value.findIndex(item => item === deleteRowData.value)
        }
        if (indexToDelete !== -1) {
          rowData.value.splice(indexToDelete, 1)
        }

        console.log('Row deleted successfully')
      } catch (error) {
        console.error('Error deleting row:', error)
      }
    }
    
    showDeleteDialog.value = false
    deleteRowData.value = null
    deleteRowNodeId.value = null
  }

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

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

    try {
      // Update the grid row via nodeId if available
      let updated = false
      if (selectedRowNodeId.value != null && gridApi.value.getRowNode) {
        const node = gridApi.value.getRowNode(selectedRowNodeId.value)
        if (node) {
          node.setData(editedData)
          updated = true
        }
      }

      // Sync local rowData list
      let indexToUpdate = -1
      if (editedData.id != null) {
        indexToUpdate = rowData.value.findIndex(item => item && item.id === editedData.id)
      }
      if (indexToUpdate === -1 && selectedRowData.value) {
        indexToUpdate = rowData.value.findIndex(item => item === selectedRowData.value)
      }
      if (indexToUpdate !== -1) {
        rowData.value[indexToUpdate] = { ...editedData }
        updated = true
      }

      if (updated) {
        console.log('Row updated successfully:', editedData)
      } else {
        console.error('Row not found for update')
      }
    } catch (error) {
      console.error('Error updating user:', error)
    }

    showDetailsDialog.value = false
    selectedRowData.value = null
    selectedRowNodeId.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) {
      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
      })
    } else {
      console.warn('Excel export not available - requires AG Grid Enterprise')
    }
  }

  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
  }
}