/**
 * MultiSigAdmin Component - Multi-sig admin interface with approval workflow
 */

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

interface MultiSigProposal {
  id: string
  contractAddress: string
  functionName: string
  args: any[]
  description: string
  approvals: string[]
  requiredApprovals: number
  status: 'pending' | 'approved' | 'executed'
  createdAt: number
}

export default function MultiSigAdmin() {
  const { address } = useAccount()
  const { createAdminAction, addAuditLog } = useAdmin()
  const [proposals, setProposals] = useState<MultiSigProposal[]>([])
  const [selectedContract, setSelectedContract] = useState<string>('')

  const contractAddress = CONTRACT_ADDRESSES.mainnet.MAINNET_TETHER

  useEffect(() => {
    // Load proposals from storage
    const stored = localStorage.getItem('multisig_proposals')
    if (stored) {
      setProposals(JSON.parse(stored))
    }
  }, [])

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

  const createProposal = (functionName: string, args: any[], description: string) => {
    if (!address) {
      toast.error('Please connect your wallet')
      return
    }

    const proposal: MultiSigProposal = {
      id: `proposal_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`,
      contractAddress: selectedContract || contractAddress,
      functionName,
      args,
      description,
      approvals: [address],
      requiredApprovals: 2, // Default threshold
      status: 'pending',
      createdAt: Date.now(),
    }

    setProposals((prev) => [...prev, proposal])
    toast.success('Proposal created. Waiting for approvals...')

    // Create admin action
    createAdminAction({
      type: functionName as any,
      contractAddress: proposal.contractAddress,
      functionName,
      args,
      status: TransactionRequestStatus.PENDING,
      createdAt: Date.now(),
      id: generateSecureId(),
    })

    addAuditLog({
      user: address,
      action: 'create_proposal',
      resourceType: 'multisig_proposal',
      resourceId: proposal.id,
      details: { functionName, description },
      status: 'success',
    })
  }

  const approveProposal = (proposalId: string) => {
    if (!address) {
      toast.error('Please connect your wallet')
      return
    }

    setProposals((prev) =>
      prev.map((p) => {
        if (p.id === proposalId) {
          const newApprovals = [...p.approvals, address]
          const isApproved = newApprovals.length >= p.requiredApprovals
          return {
            ...p,
            approvals: newApprovals,
            status: isApproved ? 'approved' : 'pending',
          }
        }
        return p
      })
    )

    toast.success('Proposal approved')
    addAuditLog({
      user: address,
      action: 'approve_proposal',
      resourceType: 'multisig_proposal',
      resourceId: proposalId,
      status: 'success',
    })
  }

  const executeProposal = async (proposal: MultiSigProposal) => {
    if (proposal.status !== 'approved') {
      toast.error('Proposal must be approved before execution')
      return
    }

    // Confirm execution
    const confirmed = window.confirm(
      `Execute proposal "${proposal.description}"?\n\n` +
        `Function: ${proposal.functionName}\n` +
        `Contract: ${proposal.contractAddress}\n` +
        `Approvals: ${proposal.approvals.length}/${proposal.requiredApprovals}`
    )

    if (!confirmed) return

    try {
      // In production, this would execute the transaction via Safe SDK
      // For now, we simulate the execution
      // TODO: Integrate Safe SDK for actual execution
      // const safeSdk = await getSafeSdk()
      // const safeTransaction = await safeSdk.createTransaction({
      //   safeTransactionData: {
      //     to: proposal.contractAddress,
      //     value: '0',
      //     data: encodeFunctionData(...),
      //   },
      // })
      // const executeTxResponse = await safeSdk.executeTransaction(safeTransaction)
      // await executeTxResponse.transactionResponse?.wait()

      setProposals((prev) =>
        prev.map((p) => (p.id === proposal.id ? { ...p, status: 'executed' } : p))
      )

      addAuditLog({
        user: address || 'unknown',
        action: 'execute_proposal',
        resourceType: 'multisig_proposal',
        resourceId: proposal.id,
        details: { functionName: proposal.functionName, description: proposal.description },
        status: 'success',
      })

      toast.success('Proposal executed successfully')
    } catch (error: any) {
      toast.error(`Execution failed: ${error.message}`)
      console.error('Proposal execution error:', error)
    }
  }

  const pendingProposals = proposals.filter((p) => p.status === 'pending' || p.status === 'approved')

  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">Multi-Signature Admin</h2>
        <p className="text-white/70 text-sm mb-4">
          Create proposals for admin actions that require multiple approvals before execution.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Contract Address</label>
            <select
              value={selectedContract}
              onChange={(e) => setSelectedContract(e.target.value)}
              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"
            >
              <option value={contractAddress}>MainnetTether ({contractAddress.slice(0, 10)}...)</option>
              <option value={CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR}>
                TransactionMirror ({CONTRACT_ADDRESSES.mainnet.TRANSACTION_MIRROR.slice(0, 10)}...)
              </option>
            </select>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <button
              onClick={() => createProposal('pause', [], 'Pause contract')}
              className="px-4 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-colors"
            >
              Propose Pause
            </button>
            <button
              onClick={() => createProposal('unpause', [], 'Unpause contract')}
              className="px-4 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg font-semibold transition-colors"
            >
              Propose Unpause
            </button>
            <button
              onClick={() => {
                const newAdmin = prompt('Enter new admin address:')
                if (newAdmin) {
                  createProposal('setAdmin', [newAdmin], `Change admin to ${newAdmin.slice(0, 10)}...`)
                }
              }}
              className="px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
            >
              Propose Admin Change
            </button>
          </div>
        </div>
      </div>

      {pendingProposals.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">Pending Proposals</h3>
          <div className="space-y-4">
            {pendingProposals.map((proposal) => (
              <div
                key={proposal.id}
                className="bg-white/5 rounded-lg p-4 border border-white/10"
              >
                <div className="flex justify-between items-start mb-3">
                  <div>
                    <p className="text-white font-semibold">{proposal.description}</p>
                    <p className="text-white/60 text-xs mt-1">
                      Contract: {proposal.contractAddress.slice(0, 20)}...
                    </p>
                    <p className="text-white/60 text-xs">
                      Function: {proposal.functionName}
                    </p>
                  </div>
                  <span
                    className={`px-3 py-1 rounded-full text-xs font-semibold ${
                      proposal.status === 'approved'
                        ? 'bg-green-500/20 text-green-300'
                        : 'bg-yellow-500/20 text-yellow-300'
                    }`}
                  >
                    {proposal.status === 'approved' ? 'Approved' : 'Pending'}
                  </span>
                </div>

                <div className="mb-3">
                  <div className="flex justify-between text-sm mb-1">
                    <span className="text-white/70">Approvals:</span>
                    <span className="text-white">
                      {proposal.approvals.length} / {proposal.requiredApprovals}
                    </span>
                  </div>
                  <div className="w-full bg-white/10 rounded-full h-2">
                    <div
                      className="bg-blue-500 h-2 rounded-full transition-all"
                      style={{
                        width: `${(proposal.approvals.length / proposal.requiredApprovals) * 100}%`,
                      }}
                    />
                  </div>
                </div>

                <div className="flex gap-2">
                  {!proposal.approvals.includes(address || '') && (
                    <button
                      onClick={() => approveProposal(proposal.id)}
                      className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
                    >
                      Approve
                    </button>
                  )}
                  {proposal.status === 'approved' && (
                    <button
                      onClick={() => executeProposal(proposal)}
                      className="flex-1 px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg font-semibold transition-colors"
                    >
                      Execute
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
