/**
 * TransactionQueue Component - Transaction queue management UI
 */

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

export default function TransactionQueue() {
  const { adminActions, updateAdminAction } = useAdmin()
  const [filter, setFilter] = useState<'all' | 'pending' | 'approved' | 'executed' | 'failed'>('all')
  const [currentPage, setCurrentPage] = useState(1)
  const [itemsPerPage, setItemsPerPage] = useState(25)

  const filteredActions = useMemo(() => {
    return adminActions.filter((action) => {
      if (filter === 'all') return true
      if (filter === 'pending') return action.status === TransactionRequestStatus.PENDING
      if (filter === 'approved') return action.status === TransactionRequestStatus.APPROVED
      if (filter === 'executed') return action.status === TransactionRequestStatus.SUCCESS
      if (filter === 'failed') return action.status === TransactionRequestStatus.FAILED
      return true
    })
  }, [adminActions, filter])

  // Pagination
  const totalPages = Math.ceil(filteredActions.length / itemsPerPage)
  const paginatedActions = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage
    const end = start + itemsPerPage
    return filteredActions.slice(start, end)
  }, [filteredActions, currentPage, itemsPerPage])

  // Reset to page 1 when filter changes
  useEffect(() => {
    setCurrentPage(1)
  }, [filter])

  const handleRetry = (actionId: string) => {
    updateAdminAction(actionId, {
      status: TransactionRequestStatus.PENDING,
      error: undefined,
    })
    toast.success('Transaction queued for retry')
  }

  const handleCancel = (actionId: string) => {
    updateAdminAction(actionId, {
      status: TransactionRequestStatus.REJECTED,
    })
    toast.success('Transaction cancelled')
  }

  const getStatusColor = (status: TransactionRequestStatus) => {
    switch (status) {
      case TransactionRequestStatus.PENDING:
        return 'bg-yellow-500/20 text-yellow-300'
      case TransactionRequestStatus.APPROVED:
        return 'bg-blue-500/20 text-blue-300'
      case TransactionRequestStatus.SUCCESS:
        return 'bg-green-500/20 text-green-300'
      case TransactionRequestStatus.FAILED:
        return 'bg-red-500/20 text-red-300'
      case TransactionRequestStatus.REJECTED:
        return 'bg-gray-500/20 text-gray-300'
      default:
        return 'bg-gray-500/20 text-gray-300'
    }
  }

  return (
    <div className="bg-black/20 rounded-xl p-6 border border-white/10">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold text-white">Transaction Queue</h2>
        <div className="flex gap-2">
          {(['all', 'pending', 'approved', 'executed', 'failed'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1 rounded-lg text-sm font-semibold transition-colors ${
                filter === f
                  ? 'bg-blue-600 text-white'
                  : 'bg-white/10 text-white/70 hover:bg-white/20'
              }`}
            >
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {paginatedActions.length === 0 ? (
        <div className="text-center py-8 text-white/60">
          <p>No transactions found</p>
        </div>
      ) : (
        <>
          <div className="space-y-3">
            {paginatedActions.map((action) => (
              <div
                key={action.id}
                className="bg-white/5 rounded-lg p-4 border border-white/10"
              >
                <div className="flex justify-between items-start mb-2">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-white font-semibold">{action.type}</span>
                      <span className={`px-2 py-1 rounded text-xs font-semibold ${getStatusColor(action.status)}`}>
                        {action.status}
                      </span>
                    </div>
                    <p className="text-white/60 text-xs font-mono">
                      Contract: {action.contractAddress.slice(0, 20)}...
                    </p>
                    <p className="text-white/60 text-xs">
                      Function: {action.functionName}
                    </p>
                    {action.hash && (
                      <a
                        href={`https://etherscan.io/tx/${action.hash}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-400 hover:text-blue-300 text-xs underline"
                      >
                        View on Etherscan
                      </a>
                    )}
                    {action.error && (
                      <p className="text-red-400 text-xs mt-1">Error: {action.error}</p>
                    )}
                  </div>
                  <div className="flex gap-2">
                    {action.status === TransactionRequestStatus.FAILED && (
                      <button
                        onClick={() => handleRetry(action.id)}
                        className="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded text-xs font-semibold"
                      >
                        Retry
                      </button>
                    )}
                    {(action.status === TransactionRequestStatus.PENDING ||
                      action.status === TransactionRequestStatus.APPROVED) && (
                      <button
                        onClick={() => handleCancel(action.id)}
                        className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-xs font-semibold"
                      >
                        Cancel
                      </button>
                    )}
                  </div>
                </div>
                <div className="text-white/50 text-xs">
                  Created: {new Date(action.createdAt).toLocaleString()}
                  {action.executedAt && (
                    <> | Executed: {new Date(action.executedAt).toLocaleString()}</>
                  )}
                </div>
              </div>
            ))}
          </div>
          {filteredActions.length > itemsPerPage && (
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
              itemsPerPage={itemsPerPage}
              totalItems={filteredActions.length}
              onItemsPerPageChange={setItemsPerPage}
            />
          )}
        </>
      )}
    </div>
  )
}
