/**
 * TimeLockedActions Component - Time delays for sensitive operations
 */

import { useState, useEffect } from 'react'
import { useAdmin } from '../../contexts/AdminContext'
import { TransactionRequestStatus } from '../../types/admin'
import { generateSecureId } from '../../utils/security'
import { CONTRACT_ADDRESSES } from '../../config/contracts'
import toast from 'react-hot-toast'

interface TimeLockedAction {
  id: string
  action: string
  contractAddress: string
  scheduledTime: number
  status: 'pending' | 'executed' | 'cancelled'
}

export default function TimeLockedActions() {
  const { createAdminAction, addAuditLog } = useAdmin()
  const [lockedActions, setLockedActions] = useState<TimeLockedAction[]>([])
  const [delayMinutes, setDelayMinutes] = useState(60)

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

  useEffect(() => {
    localStorage.setItem('time_locked_actions', JSON.stringify(lockedActions))

    // Check for actions ready to execute
    const checkActions = () => {
      const now = Date.now()
      lockedActions.forEach((action) => {
        if (action.status === 'pending' && action.scheduledTime <= now) {
          // Execute action
          createAdminAction({
            type: action.action as any,
            contractAddress: action.contractAddress,
            functionName: action.action,
            args: [],
            status: TransactionRequestStatus.PENDING,
            createdAt: Date.now(),
            id: generateSecureId(),
          })
          setLockedActions((prev) =>
            prev.map((a) => (a.id === action.id ? { ...a, status: 'executed' } : a))
          )
          toast.success(`Time-locked action "${action.action}" executed`)
        }
      })
    }

    const interval = setInterval(checkActions, 10000) // Check every 10 seconds
    return () => clearInterval(interval)
  }, [lockedActions, createAdminAction])

  const scheduleAction = (action: string, contractAddress: string) => {
    const scheduledTime = Date.now() + delayMinutes * 60 * 1000
    const newAction: TimeLockedAction = {
      id: `timelock_${Date.now()}`,
      action,
      contractAddress,
      scheduledTime,
      status: 'pending',
    }

    setLockedActions((prev) => [...prev, newAction])
    toast.success(`Action scheduled for ${new Date(scheduledTime).toLocaleString()}`)

    addAuditLog({
      user: 'admin',
      action: 'schedule_timelocked',
      resourceType: 'timelock',
      resourceId: newAction.id,
      details: { action, scheduledTime },
      status: 'success',
    })
  }

  const cancelAction = (id: string) => {
    setLockedActions((prev) =>
      prev.map((a) => (a.id === id ? { ...a, status: 'cancelled' } : a))
    )
    toast.success('Action cancelled')
  }

  const pendingActions = lockedActions.filter((a) => a.status === 'pending')

  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">Time-Locked Actions</h2>
        <p className="text-white/70 text-sm mb-4">
          Schedule sensitive admin actions with a time delay for additional security.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Delay (minutes)</label>
            <input
              type="number"
              value={delayMinutes}
              onChange={(e) => setDelayMinutes(parseInt(e.target.value) || 0)}
              min="0"
              className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-blue-500"
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <button
              onClick={() =>
                scheduleAction('setAdmin', CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER as string)
              }
              className="px-4 py-3 bg-yellow-600 hover:bg-yellow-700 text-white rounded-lg font-semibold transition-colors"
            >
              Schedule Admin Change
            </button>
            <button
              onClick={() =>
                scheduleAction('pause', CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER as string)
              }
              className="px-4 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-colors"
            >
              Schedule Pause
            </button>
          </div>
        </div>
      </div>

      {pendingActions.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">Scheduled Actions</h3>
          <div className="space-y-3">
            {pendingActions.map((action) => {
              const timeRemaining = Math.max(0, action.scheduledTime - Date.now())
              const minutes = Math.floor(timeRemaining / 60000)
              const seconds = Math.floor((timeRemaining % 60000) / 1000)

              return (
                <div
                  key={action.id}
                  className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4"
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <p className="text-white font-semibold">{action.action}</p>
                      <p className="text-white/60 text-xs font-mono mt-1">
                        {action.contractAddress.slice(0, 20)}...
                      </p>
                      <p className="text-yellow-200 text-xs mt-2">
                        Scheduled: {new Date(action.scheduledTime).toLocaleString()}
                      </p>
                      <p className="text-yellow-200 text-xs">
                        Time remaining: {minutes}m {seconds}s
                      </p>
                    </div>
                    <button
                      onClick={() => cancelAction(action.id)}
                      className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-sm font-semibold"
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}
