/**
 * TransactionQueuePriority Component - Priority levels and queue management
 */

import { useState, useEffect } from 'react'
import { useAdmin } from '../../contexts/AdminContext'
import { TransactionRequestStatus } from '../../types/admin'
import toast from 'react-hot-toast'

export enum QueuePriority {
  LOW = 'LOW',
  NORMAL = 'NORMAL',
  HIGH = 'HIGH',
  URGENT = 'URGENT',
}

interface QueuedTransaction {
  id: string
  actionId: string
  priority: QueuePriority
  createdAt: number
}

export default function TransactionQueuePriority() {
  const { adminActions } = useAdmin()
  const [queuedTransactions, setQueuedTransactions] = useState<QueuedTransaction[]>([])
  const [priorityFilter, setPriorityFilter] = useState<QueuePriority | 'all'>('all')

  useEffect(() => {
    const stored = localStorage.getItem('queued_transactions')
    if (stored) {
      setQueuedTransactions(JSON.parse(stored))
    }
  }, [])

  useEffect(() => {
    localStorage.setItem('queued_transactions', JSON.stringify(queuedTransactions))
  }, [queuedTransactions])

  const addToQueue = (actionId: string, priority: QueuePriority) => {
    const action = adminActions.find((a) => a.id === actionId)
    if (!action) {
      toast.error('Action not found')
      return
    }

    if (queuedTransactions.some((q) => q.actionId === actionId)) {
      toast.error('Action already in queue')
      return
    }

    const queued: QueuedTransaction = {
      id: `queue_${Date.now()}`,
      actionId,
      priority,
      createdAt: Date.now(),
    }

    setQueuedTransactions((prev) => [...prev, queued])
    toast.success('Action added to queue')
  }

  const removeFromQueue = (queueId: string) => {
    setQueuedTransactions((prev) => prev.filter((q) => q.id !== queueId))
    toast.success('Removed from queue')
  }

  const executeNext = () => {
    const sorted = [...queuedTransactions].sort((a, b) => {
      const priorityOrder = {
        [QueuePriority.URGENT]: 4,
        [QueuePriority.HIGH]: 3,
        [QueuePriority.NORMAL]: 2,
        [QueuePriority.LOW]: 1,
      }
      return priorityOrder[b.priority] - priorityOrder[a.priority]
    })

    if (sorted.length === 0) {
      toast.error('Queue is empty')
      return
    }

    const next = sorted[0]
    const action = adminActions.find((a) => a.id === next.actionId)
    if (action) {
      toast(`Executing: ${action.functionName} (${next.priority} priority)`, { icon: '⚡' })
      // In production, this would trigger execution
    }
  }

  const pendingActions = adminActions.filter(
    (a) => a.status === TransactionRequestStatus.PENDING
  )

  const filteredQueue = queuedTransactions.filter(
    (q) => priorityFilter === 'all' || q.priority === priorityFilter
  )

  const getPriorityColor = (priority: QueuePriority) => {
    switch (priority) {
      case QueuePriority.URGENT:
        return 'bg-red-500/20 text-red-300 border-red-500/50'
      case QueuePriority.HIGH:
        return 'bg-orange-500/20 text-orange-300 border-orange-500/50'
      case QueuePriority.NORMAL:
        return 'bg-blue-500/20 text-blue-300 border-blue-500/50'
      case QueuePriority.LOW:
        return 'bg-gray-500/20 text-gray-300 border-gray-500/50'
    }
  }

  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">Transaction Queue</h2>
        <p className="text-white/70 text-sm mb-4">
          Manage transaction queue with priority levels.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Pending Actions</label>
            <div className="space-y-2 max-h-40 overflow-y-auto">
              {pendingActions.length === 0 ? (
                <p className="text-white/60 text-sm">No pending actions</p>
              ) : (
                pendingActions.map((action) => (
                  <div
                    key={action.id}
                    className="flex items-center justify-between bg-white/5 rounded-lg p-3"
                  >
                    <div className="flex-1">
                      <p className="text-white font-semibold text-sm">{action.functionName}</p>
                      <p className="text-white/60 text-xs font-mono">
                        {action.contractAddress.slice(0, 20)}...
                      </p>
                    </div>
                    <div className="flex gap-2">
                      {Object.values(QueuePriority).map((priority) => (
                        <button
                          key={priority}
                          onClick={() => addToQueue(action.id, priority)}
                          className={`px-2 py-1 rounded text-xs font-semibold ${
                            priority === QueuePriority.URGENT
                              ? 'bg-red-600 hover:bg-red-700'
                              : priority === QueuePriority.HIGH
                              ? 'bg-orange-600 hover:bg-orange-700'
                              : priority === QueuePriority.NORMAL
                              ? 'bg-blue-600 hover:bg-blue-700'
                              : 'bg-gray-600 hover:bg-gray-700'
                          } text-white`}
                        >
                          {priority}
                        </button>
                      ))}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          <div className="flex gap-2">
            {(['all', ...Object.values(QueuePriority)] as const).map((filter) => (
              <button
                key={filter}
                onClick={() => setPriorityFilter(filter)}
                className={`px-3 py-1 rounded-lg text-sm font-semibold transition-colors ${
                  priorityFilter === filter
                    ? 'bg-blue-600 text-white'
                    : 'bg-white/10 text-white/70 hover:bg-white/20'
                }`}
              >
                {filter}
              </button>
            ))}
          </div>

          <button
            onClick={executeNext}
            disabled={filteredQueue.length === 0}
            className="w-full px-6 py-3 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
          >
            Execute Next ({filteredQueue.length} in queue)
          </button>
        </div>
      </div>

      {filteredQueue.length > 0 && (
        <div className="bg-black/20 rounded-xl p-6 border border-white/10">
          <h3 className="text-lg font-bold text-white mb-4">Queued Transactions</h3>
          <div className="space-y-2">
            {filteredQueue
              .sort((a, b) => {
                const priorityOrder = {
                  [QueuePriority.URGENT]: 4,
                  [QueuePriority.HIGH]: 3,
                  [QueuePriority.NORMAL]: 2,
                  [QueuePriority.LOW]: 1,
                }
                return priorityOrder[b.priority] - priorityOrder[a.priority]
              })
              .map((queued) => {
                const action = adminActions.find((a) => a.id === queued.actionId)
                return (
                  <div
                    key={queued.id}
                    className={`rounded-lg p-4 border ${getPriorityColor(queued.priority)}`}
                  >
                    <div className="flex justify-between items-start">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-semibold">{queued.priority}</span>
                          {action && (
                            <>
                              <span className="text-sm">{action.functionName}</span>
                              <span className="text-xs font-mono">
                                {action.contractAddress.slice(0, 10)}...
                              </span>
                            </>
                          )}
                        </div>
                        <p className="text-xs opacity-70">
                          Queued: {new Date(queued.createdAt).toLocaleString()}
                        </p>
                      </div>
                      <button
                        onClick={() => removeFromQueue(queued.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>
  )
}
