/**
 * RoleBasedAccess Component - Role-based admin access control
 */

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

export enum AdminRole {
  SUPER_ADMIN = 'SUPER_ADMIN',
  OPERATOR = 'OPERATOR',
  VIEWER = 'VIEWER',
}

interface RolePermission {
  role: AdminRole
  canPause: boolean
  canUnpause: boolean
  canSetAdmin: boolean
  canViewAuditLogs: boolean
  canUseEmergency: boolean
  canCreateTemplates: boolean
}

const ROLE_PERMISSIONS: Record<AdminRole, RolePermission> = {
  [AdminRole.SUPER_ADMIN]: {
    role: AdminRole.SUPER_ADMIN,
    canPause: true,
    canUnpause: true,
    canSetAdmin: true,
    canViewAuditLogs: true,
    canUseEmergency: true,
    canCreateTemplates: true,
  },
  [AdminRole.OPERATOR]: {
    role: AdminRole.OPERATOR,
    canPause: true,
    canUnpause: true,
    canSetAdmin: false,
    canViewAuditLogs: true,
    canUseEmergency: false,
    canCreateTemplates: true,
  },
  [AdminRole.VIEWER]: {
    role: AdminRole.VIEWER,
    canPause: false,
    canUnpause: false,
    canSetAdmin: false,
    canViewAuditLogs: true,
    canUseEmergency: false,
    canCreateTemplates: false,
  },
}

export default function RoleBasedAccess() {
  const { address } = useAccount()
  const { addAuditLog } = useAdmin()
  const [userRoles, setUserRoles] = useState<Record<string, AdminRole>>({})
  const [selectedAddress, setSelectedAddress] = useState('')
  const [selectedRole, setSelectedRole] = useState<AdminRole>(AdminRole.VIEWER)

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

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

  const assignRole = () => {
    if (!selectedAddress || !/^0x[a-fA-F0-9]{40}$/.test(selectedAddress)) {
      toast.error('Invalid address')
      return
    }

    setUserRoles((prev) => ({
      ...prev,
      [selectedAddress.toLowerCase()]: selectedRole,
    }))

    addAuditLog({
      user: address || 'admin',
      action: 'assign_role',
      resourceType: 'user',
      resourceId: selectedAddress,
      details: { role: selectedRole },
      status: 'success',
    })

    toast.success(`Role ${selectedRole} assigned to ${selectedAddress.slice(0, 10)}...`)
    setSelectedAddress('')
  }

  const currentUserRole = address ? userRoles[address.toLowerCase()] || AdminRole.VIEWER : AdminRole.VIEWER
  const currentPermissions = ROLE_PERMISSIONS[currentUserRole]

  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">Role-Based Access Control</h2>
        <p className="text-white/70 text-sm mb-4">
          Assign roles to control admin access levels.
        </p>

        <div className="space-y-4">
          <div>
            <label className="block text-white/70 text-sm mb-2">Your Current Role</label>
            <div className="bg-blue-500/20 border border-blue-500/50 rounded-lg p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-200 font-semibold">{currentUserRole}</p>
                  <p className="text-blue-200/70 text-xs mt-1">
                    Address: {address?.slice(0, 10)}...
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-blue-200 text-xs">Permissions:</p>
                  <p className="text-blue-200/70 text-xs">
                    {Object.entries(currentPermissions)
                      .filter(([key]) => key !== 'role')
                      .filter(([, value]) => value)
                      .map(([key]) => key.replace('can', ''))
                      .join(', ')}
                  </p>
                </div>
              </div>
            </div>
          </div>

          <div>
            <label className="block text-white/70 text-sm mb-2">Assign Role</label>
            <div className="flex gap-2">
              <input
                type="text"
                value={selectedAddress}
                onChange={(e) => setSelectedAddress(e.target.value)}
                placeholder="0x..."
                className="flex-1 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"
              />
              <select
                value={selectedRole}
                onChange={(e) => setSelectedRole(e.target.value as AdminRole)}
                className="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-blue-500"
              >
                <option value={AdminRole.SUPER_ADMIN}>Super Admin</option>
                <option value={AdminRole.OPERATOR}>Operator</option>
                <option value={AdminRole.VIEWER}>Viewer</option>
              </select>
              <button
                onClick={assignRole}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
              >
                Assign
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-black/20 rounded-xl p-6 border border-white/10">
        <h3 className="text-lg font-bold text-white mb-4">Role Permissions</h3>
        <div className="space-y-3">
          {Object.entries(ROLE_PERMISSIONS).map(([role, permissions]) => (
            <div key={role} className="bg-white/5 rounded-lg p-4">
              <h4 className="text-white font-semibold mb-2">{role}</h4>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-2 text-sm">
                {Object.entries(permissions)
                  .filter(([key]) => key !== 'role')
                  .map(([key, value]) => (
                    <div key={key} className="flex items-center gap-2">
                      <span className={value ? 'text-green-400' : 'text-red-400'}>
                        {value ? '✓' : '✗'}
                      </span>
                      <span className="text-white/70">{key.replace('can', '')}</span>
                    </div>
                  ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
