/**
 * WalletBackup Component - Encrypted wallet configuration backup
 */

import { useState } from 'react'
import { useAdmin } from '../../contexts/AdminContext'
import { SecureStorage } from '../../utils/encryption'
import { STORAGE_KEYS } from '../../utils/constants'
import toast from 'react-hot-toast'

export default function WalletBackup() {
  const { adminActions, auditLogs } = useAdmin()
  const [backupPassword, setBackupPassword] = useState('')
  const [importData, setImportData] = useState('')
  const secureStorage = new SecureStorage()

  const exportBackup = async () => {
    if (!backupPassword) {
      toast.error('Enter a password for encryption')
      return
    }

    try {
      const backup = {
        version: '1.0',
        timestamp: Date.now(),
        adminActions,
        auditLogs: auditLogs.slice(-1000), // Last 1000 logs
        wallets: JSON.parse((await secureStorage.getItem(STORAGE_KEYS.SMART_WALLETS)) || '[]'),
      }

      // Encrypt backup
      const { encryptData: encryptDataFn } = await import('../../utils/encryption')
      const encrypted = await encryptDataFn(JSON.stringify(backup), backupPassword)

      // Create download
      const blob = new Blob([encrypted], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `admin-backup-${Date.now()}.encrypted.json`
      a.click()
      URL.revokeObjectURL(url)

      toast.success('Backup exported successfully')
      setBackupPassword('')
    } catch (error: any) {
      toast.error(`Export failed: ${error.message}`)
    }
  }

  const importBackup = async () => {
    if (!importData || !backupPassword) {
      toast.error('Enter backup data and password')
      return
    }

    try {
      // Decrypt backup
      const { decryptData: decryptDataFn } = await import('../../utils/encryption')
      const decrypted = await decryptDataFn(importData, backupPassword)
      const backup = JSON.parse(decrypted)

      // Validate backup
      if (!backup.version || !backup.timestamp) {
        toast.error('Invalid backup format')
        return
      }

      // Import data (in production, this would restore to storage)
      toast.success('Backup imported successfully (preview mode)')
      console.log('Backup data:', backup)
      setImportData('')
      setBackupPassword('')
    } catch (error: any) {
      toast.error(`Import failed: ${error.message}`)
    }
  }

  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">Wallet Backup & Export</h2>
        <p className="text-white/70 text-sm mb-4">
          Export and import encrypted wallet configurations and admin data.
        </p>

        <div className="space-y-6">
          <div>
            <h3 className="text-lg font-bold text-white mb-4">Export Backup</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-white/70 text-sm mb-2">Encryption Password</label>
                <input
                  type="password"
                  value={backupPassword}
                  onChange={(e) => setBackupPassword(e.target.value)}
                  placeholder="Enter password"
                  className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
                />
              </div>
              <button
                onClick={exportBackup}
                disabled={!backupPassword}
                className="w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-lg font-semibold transition-colors"
              >
                Export Backup
              </button>
            </div>
          </div>

          <div>
            <h3 className="text-lg font-bold text-white mb-4">Import Backup</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-white/70 text-sm mb-2">Backup Data</label>
                <textarea
                  value={importData}
                  onChange={(e) => setImportData(e.target.value)}
                  placeholder="Paste encrypted backup data..."
                  rows={6}
                  className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500 font-mono text-sm"
                />
              </div>
              <div>
                <label className="block text-white/70 text-sm mb-2">Decryption Password</label>
                <input
                  type="password"
                  value={backupPassword}
                  onChange={(e) => setBackupPassword(e.target.value)}
                  placeholder="Enter password"
                  className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:border-blue-500"
                />
              </div>
              <button
                onClick={importBackup}
                disabled={!importData || !backupPassword}
                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"
              >
                Import Backup
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
