/**
 * BatchOperations Component - Batch multiple admin actions
 */

import { useState } from 'react'
import { useWriteContract } from 'wagmi'
import { mainnet } from 'wagmi/chains'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import { MAINNET_TETHER_ABI } from '../../abis/MainnetTether'
import { TRANSACTION_MIRROR_ABI } from '../../abis/TransactionMirror'
import { useAdmin } from '../../contexts/AdminContext'
import { TransactionRequestStatus } from '../../types/admin'
import { generateSecureId } from '../../utils/security'
import toast from 'react-hot-toast'

interface BatchAction {
  id: string
  contractAddress: string
  functionName: string
  args: any[]
  enabled: boolean
}

export default function BatchOperations() {
  const { createAdminAction, addAuditLog } = useAdmin()
  const [actions, setActions] = useState<BatchAction[]>([])
  const { writeContract, isPending } = useWriteContract()

  const addAction = (contractAddress: string, functionName: string, args: any[]) => {
    const newAction: BatchAction = {
      id: `action_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
      contractAddress,
      functionName,
      args,
      enabled: true,
    }
    setActions((prev) => [...prev, newAction])
  }

  const removeAction = (id: string) => {
    setActions((prev) => prev.filter((a) => a.id !== id))
  }

  const toggleAction = (id: string) => {
    setActions((prev) =>
      prev.map((a) => (a.id === id ? { ...a, enabled: !a.enabled } : a))
    )
  }

  const executeBatch = async () => {
    const enabledActions = actions.filter((a) => a.enabled)
    if (enabledActions.length === 0) {
      toast.error('No actions enabled')
      return
    }

    toast(`Executing ${enabledActions.length} actions...`, { icon: '⏳' })

    for (const action of enabledActions) {
      try {
        const abi = action.contractAddress === CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER
          ? MAINNET_TETHER_ABI
          : TRANSACTION_MIRROR_ABI

        writeContract(
          {
            address: action.contractAddress as `0x${string}`,
            abi,
            functionName: action.functionName as any,
            args: action.args as any,
            chainId: mainnet.id,
          },
          {
            onSuccess: (hash) => {
              createAdminAction({
                type: action.functionName as any,
                contractAddress: action.contractAddress,
                functionName: action.functionName,
                args: action.args,
                status: TransactionRequestStatus.SUCCESS,
                hash,
                createdAt: Date.now(),
                id: generateSecureId(),
              })
              toast.success(`Action ${action.functionName} executed`)
            },
            onError: (error: any) => {
              createAdminAction({
                type: action.functionName as any,
                contractAddress: action.contractAddress,
                functionName: action.functionName,
                args: action.args,
                status: TransactionRequestStatus.FAILED,
                error: error.message,
                createdAt: Date.now(),
                id: generateSecureId(),
              })
              toast.error(`Action ${action.functionName} failed: ${error.message}`)
            },
          }
        )

        // Small delay between actions
        await new Promise((resolve) => setTimeout(resolve, 1000))
      } catch (error: any) {
        toast.error(`Error executing ${action.functionName}: ${error.message}`)
      }
    }

    addAuditLog({
      user: 'admin',
      action: 'batch_execute',
      resourceType: 'batch_operation',
      resourceId: `batch_${Date.now()}`,
      details: { actionCount: enabledActions.length },
      status: 'success',
    })
  }

  return (
    <div className="space-y-6">
      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h2 className="text-xl font-bold text-white mb-4">Batch Operations</h2>
        <p className="text-white/70 text-sm mb-4">
          Create and execute multiple admin actions in sequence.
        </p>

        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <button
              onClick={() =>
                addAction(
                  CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
                  'pause',
                  []
                )
              }
              className="px-4 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-colors"
            >
              + Pause MainnetTether
            </button>
            <button
              onClick={() =>
                addAction(
                  CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR,
                  'pause',
                  []
                )
              }
              className="px-4 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-colors"
            >
              + Pause TransactionMirror
            </button>
            <button
              onClick={() =>
                addAction(
                  CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER,
                  'unpause',
                  []
                )
              }
              className="px-4 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg font-semibold transition-colors"
            >
              + Unpause MainnetTether
            </button>
          </div>

          {actions.length > 0 && (
            <div className="mt-6">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-bold text-white">
                  Batch Actions ({actions.filter((a) => a.enabled).length} enabled)
                </h3>
                <button
                  onClick={executeBatch}
                  disabled={isPending || actions.filter((a) => a.enabled).length === 0}
                  className="px-6 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
                >
                  {isPending ? 'Executing...' : 'Execute Batch'}
                </button>
              </div>

              <div className="space-y-2">
                {actions.map((action) => (
                  <div
                    key={action.id}
                    className="bg-white/5 rounded-lg p-4 border border-white/10 flex items-center justify-between"
                  >
                    <div className="flex items-center gap-3 flex-1">
                      <input
                        type="checkbox"
                        checked={action.enabled}
                        onChange={() => toggleAction(action.id)}
                        className="w-5 h-5"
                      />
                      <div className="flex-1">
                        <p className="text-white font-semibold">{action.functionName}</p>
                        <p className="text-white/60 text-xs font-mono">
                          {action.contractAddress.slice(0, 20)}...
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() => removeAction(action.id)}
                      className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-sm font-semibold"
                    >
                      Remove
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
