"use client"

import React from 'react'
import { Loader2, MoreHorizontal, AlertTriangle } from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog'
import { Button } from '../ui/button'
import { Badge } from '../ui/badge'
import { cn } from '../../lib/utils'

export interface BulkAction<T = any> {
  label: string
  icon?: React.ReactNode
  action: (selectedRows: T[]) => void | Promise<void>
  confirmMessage?: string
  confirmTitle?: string
  variant?: 'default' | 'destructive'
  disabled?: boolean | ((selectedRows: T[]) => boolean)
}

interface DataTableBulkActionsProps<T = any> {
  selectedRows: T[]
  actions: BulkAction<T>[]
  onClearSelection?: () => void
  className?: string
}

export function DataTableBulkActions<T>({
  selectedRows,
  actions,
  onClearSelection,
  className
}: DataTableBulkActionsProps<T>) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [pendingAction, setPendingAction] = React.useState<BulkAction<T> | null>(null)
  
  const selectedCount = selectedRows.length

  const handleAction = async (action: BulkAction<T>) => {
    if (action.confirmMessage) {
      setPendingAction(action)
      return
    }

    await executeAction(action)
  }

  const executeAction = async (action: BulkAction<T>) => {
    setIsLoading(true)
    try {
      await action.action(selectedRows)
      
      // Clear selection after successful action
      if (onClearSelection) {
        onClearSelection()
      }
    } catch (error) {
      console.error('Bulk action failed:', error)
      // You might want to show an error toast here
    } finally {
      setIsLoading(false)
      setPendingAction(null)
    }
  }

  const handleConfirm = async () => {
    if (pendingAction) {
      await executeAction(pendingAction)
    }
  }

  if (selectedCount === 0) {
    return null
  }

  return (
    <>
      <div className={cn("flex items-center gap-2", className)}>
        {/* Selected count badge */}
        <Badge variant="secondary" className="gap-1">
          <span className="font-semibold">{selectedCount}</span>
          <span>selected</span>
        </Badge>

        {/* Bulk actions dropdown */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="outline"
              size="sm"
              disabled={isLoading}
              className="gap-2"
            >
              {isLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Processing...
                </>
              ) : (
                <>
                  <MoreHorizontal className="h-4 w-4" />
                  Bulk Actions
                </>
              )}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-48">
            {actions.map((action, index) => {
              const isDisabled = typeof action.disabled === 'function'
                ? action.disabled(selectedRows)
                : action.disabled

              return (
                <DropdownMenuItem
                  key={index}
                  disabled={isDisabled || isLoading}
                  onSelect={() => handleAction(action)}
                  className={cn(
                    "cursor-pointer",
                    action.variant === 'destructive' && "text-destructive focus:text-destructive"
                  )}
                >
                  {action.icon && (
                    <span className="mr-2 h-4 w-4">{action.icon}</span>
                  )}
                  {action.label}
                </DropdownMenuItem>
              )
            })}
            
            {onClearSelection && (
              <>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onSelect={onClearSelection}
                  className="cursor-pointer text-muted-foreground"
                >
                  Clear selection
                </DropdownMenuItem>
              </>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* Confirmation dialog */}
      <AlertDialog 
        open={!!pendingAction} 
        onOpenChange={(open) => !open && setPendingAction(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              {pendingAction?.variant === 'destructive' && (
                <AlertTriangle className="h-5 w-5 text-destructive" />
              )}
              {pendingAction?.confirmTitle || 'Confirm Action'}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {pendingAction?.confirmMessage || 
                `This action will affect ${selectedCount} selected item${selectedCount > 1 ? 's' : ''}. This action cannot be undone.`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isLoading}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirm}
              disabled={isLoading}
              className={cn(
                pendingAction?.variant === 'destructive' && "bg-destructive text-destructive-foreground hover:bg-destructive/90"
              )}
            >
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Processing...
                </>
              ) : (
                'Confirm'
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}