/**
 * OwnerManagement Component - Configure owners, thresholds, permissions
 */

import { useState, useEffect } from 'react'
import { useAccount } from 'wagmi'
import { useAdmin } from '../../contexts/AdminContext'
import { validateAddress } from '../../utils/security'
import toast from 'react-hot-toast'

interface WalletOwner {
  address: string
  label?: string
  addedAt: number
}

interface WalletConfig {
  id: string
  address: string
  owners: WalletOwner[]
  threshold: number
}

export default function OwnerManagement() {
  const { address } = useAccount()
  const { addAuditLog } = useAdmin()
  const [wallets, setWallets] = useState<WalletConfig[]>([])
  const [selectedWallet, setSelectedWallet] = useState<string>('')
  const [newOwner, setNewOwner] = useState('')
  const [ownerLabel, setOwnerLabel] = useState('')
  const [threshold, setThreshold] = useState(1)

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

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

  const addOwner = () => {
    if (!selectedWallet) {
      toast.error('Select a wallet first')
      return
    }

    const validation = validateAddress(newOwner)
    if (!validation.valid) {
      toast.error(validation.error || 'Invalid address')
      return
    }

    const wallet = wallets.find((w) => w.id === selectedWallet)
    if (!wallet) return

    if (wallet.owners.some((o) => o.address.toLowerCase() === newOwner.toLowerCase())) {
      toast.error('Owner already exists')
      return
    }

    const newOwnerObj: WalletOwner = {
      address: validation.checksummed || newOwner,
      label: ownerLabel || undefined,
      addedAt: Date.now(),
    }

    setWallets((prev) =>
      prev.map((w) =>
        w.id === selectedWallet
          ? { ...w, owners: [...w.owners, newOwnerObj] }
          : w
      )
    )

    addAuditLog({
      user: address || 'admin',
      action: 'add_owner',
      resourceType: 'wallet',
      resourceId: selectedWallet,
      details: { owner: newOwnerObj.address },
      status: 'success',
    })

    toast.success('Owner added')
    setNewOwner('')
    setOwnerLabel('')
  }

  const removeOwner = (walletId: string, ownerAddress: string) => {
    const wallet = wallets.find((w) => w.id === walletId)
    if (!wallet) return

    if (wallet.owners.length <= 1) {
      toast.error('Cannot remove last owner')
      return
    }

    setWallets((prev) =>
      prev.map((w) =>
        w.id === walletId
          ? {
              ...w,
              owners: w.owners.filter((o) => o.address !== ownerAddress),
              threshold: Math.min(w.threshold, w.owners.length - 1),
            }
          : w
      )
    )

    toast.success('Owner removed')
  }

  const updateThreshold = (walletId: string, newThreshold: number) => {
    const wallet = wallets.find((w) => w.id === walletId)
    if (!wallet) return

    if (newThreshold < 1 || newThreshold > wallet.owners.length) {
      toast.error('Invalid threshold')
      return
    }

    setWallets((prev) =>
      prev.map((w) => (w.id === walletId ? { ...w, threshold: newThreshold } : w))
    )

    toast.success('Threshold updated')
  }

  const selectedWalletData = wallets.find((w) => w.id === selectedWallet)

  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">Owner Management</h2>
        <p className="text-white/70 text-sm mb-4">
          Manage owners and thresholds for multi-sig wallets.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Select Wallet</label>
            <select
              value={selectedWallet}
              onChange={(e) => setSelectedWallet(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="">Select a wallet...</option>
              {wallets.map((wallet) => (
                <option key={wallet.id} value={wallet.id}>
                  {wallet.address.slice(0, 20)}... ({wallet.owners.length} owners)
                </option>
              ))}
            </select>
          </div>

          {selectedWalletData && (
            <>
              <div className="bg-white/5 rounded-lg p-4">
                <div className="flex justify-between items-center mb-3">
                  <span className="text-white/70 text-sm">Current Threshold:</span>
                  <span className="text-white font-semibold">
                    {selectedWalletData.threshold} of {selectedWalletData.owners.length}
                  </span>
                </div>
                <input
                  type="number"
                  value={threshold}
                  onChange={(e) => setThreshold(parseInt(e.target.value) || 1)}
                  min="1"
                  max={selectedWalletData.owners.length}
                  className="w-full px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white"
                />
                <button
                  onClick={() => updateThreshold(selectedWallet, threshold)}
                  className="w-full mt-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
                >
                  Update Threshold
                </button>
              </div>

              <div>
                <label className="block text-white/70 text-sm mb-2">Add Owner</label>
                <div className="space-y-2">
                  <input
                    type="text"
                    value={newOwner}
                    onChange={(e) => setNewOwner(e.target.value)}
                    placeholder="0x..."
                    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"
                  />
                  <input
                    type="text"
                    value={ownerLabel}
                    onChange={(e) => setOwnerLabel(e.target.value)}
                    placeholder="Owner label (optional)"
                    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"
                  />
                  <button
                    onClick={addOwner}
                    className="w-full px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg font-semibold transition-colors"
                  >
                    Add Owner
                  </button>
                </div>
              </div>

              <div>
                <h3 className="text-white font-semibold mb-2">Current Owners</h3>
                <div className="space-y-2">
                  {selectedWalletData.owners.map((owner, index) => (
                    <div
                      key={index}
                      className="flex items-center justify-between bg-white/5 rounded-lg p-3"
                    >
                      <div className="flex-1">
                        <p className="text-white font-mono text-sm">{owner.address}</p>
                        {owner.label && (
                          <p className="text-white/60 text-xs">{owner.label}</p>
                        )}
                      </div>
                      {selectedWalletData.owners.length > 1 && (
                        <button
                          onClick={() => removeOwner(selectedWallet, owner.address)}
                          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>
    </div>
  )
}
