'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Shield, Users, Eye, Search, Plus, Edit, Trash2 } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface Role {
  _id: string
  name: string
  displayName?: string
  description: string
  level: number
  permissions: string[]
  capabilities: string[]
  isActive: boolean
  createdAt: string
}

export default function RolesPage() {
  const router = useRouter()
  const [roles, setRoles] = useState<Role[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedRole, setSelectedRole] = useState<Role | null>(null)

  useEffect(() => {
    // Check authentication
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchRoles()
  }, [router])

  const fetchRoles = async () => {
    try {
      const result = await apiGet<Role[]>('/roles')
      if (result.success && result.data) {
        setRoles(result.data)
      }
    } catch (error: any) {
      console.error('Error fetching roles:', error)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
    } finally {
      setLoading(false)
    }
  }

  const getLevelColor = (level: number) => {
    if (level >= 90) return 'from-red-500 to-red-600'
    if (level >= 70) return 'from-orange-500 to-orange-600'
    if (level >= 50) return 'from-blue-500 to-blue-600'
    return 'from-gray-500 to-gray-600'
  }

  const getLevelName = (level: number) => {
    if (level >= 90) return 'Super Admin'
    if (level >= 70) return 'Manager'
    if (level >= 50) return 'Senior'
    if (level >= 30) return 'Staff'
    return 'Basic'
  }

  const filteredRoles = roles.filter(role =>
    role.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    role.description.toLowerCase().includes(searchTerm.toLowerCase())
  )

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Roles Management</h1>
          <p className="text-white/70">Manage user roles and permissions</p>
        </div>
        <button
          onClick={() => router.push('/admin/roles/new')}
          className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
        >
          <Plus className="w-5 h-5" />
          New Role
        </button>
      </div>

      {/* Search */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
          <input
            type="text"
            placeholder="Search roles..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
      </div>

      {/* Roles Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredRoles.map((role) => (
          <div
            key={role._id}
            className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20 hover:border-white/40 transition-all"
          >
            {/* Role Header */}
            <div className="flex items-start justify-between mb-4">
              <div className={`p-3 bg-gradient-to-br ${getLevelColor(role.level)} rounded-lg`}>
                <Shield className="w-6 h-6 text-white" />
              </div>
              <div className="flex items-center gap-2">
                {role.isActive ? (
                  <span className="px-2 py-1 bg-green-500/20 text-green-400 text-xs font-medium rounded">
                    Active
                  </span>
                ) : (
                  <span className="px-2 py-1 bg-gray-500/20 text-gray-400 text-xs font-medium rounded">
                    Inactive
                  </span>
                )}
              </div>
            </div>

            {/* Role Info */}
            <h3 className="text-white font-bold text-xl mb-2">
              {role.displayName || role.name.replace(/_/g, ' ')}
            </h3>
            <p className="text-white/70 text-sm mb-4 line-clamp-2">
              {role.description}
            </p>

            {/* Role Stats */}
            <div className="grid grid-cols-2 gap-3 mb-4">
              <div className="bg-white/5 rounded-lg p-3">
                <p className="text-white/50 text-xs mb-1">Level</p>
                <p className="text-white font-semibold">{getLevelName(role.level)}</p>
              </div>
              <div className="bg-white/5 rounded-lg p-3">
                <p className="text-white/50 text-xs mb-1">Permissions</p>
                <p className="text-white font-semibold">{role.permissions?.length || 0}</p>
              </div>
            </div>

            {/* Capabilities Badge */}
            {role.capabilities && role.capabilities.length > 0 && (
              <div className="mb-4">
                <p className="text-white/50 text-xs mb-2">Capabilities:</p>
                <div className="flex flex-wrap gap-1">
                  {role.capabilities.slice(0, 3).map((cap, idx) => (
                    <span key={idx} className="px-2 py-1 bg-primary/20 text-primary text-xs rounded">
                      {cap.split('_').slice(-1)[0].toLowerCase()}
                    </span>
                  ))}
                  {role.capabilities.length > 3 && (
                    <span className="px-2 py-1 bg-white/10 text-white/70 text-xs rounded">
                      +{role.capabilities.length - 3}
                    </span>
                  )}
                </div>
              </div>
            )}

            {/* Actions */}
            <div className="flex items-center gap-2 pt-4 border-t border-white/10">
              <button
                onClick={() => setSelectedRole(role)}
                className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded-lg transition-all"
              >
                <Eye className="w-4 h-4" />
                View
              </button>
              <button
                onClick={() => router.push(`/admin/roles/${role._id}`)}
                className="flex-1 flex items-center justify-center gap-2 px-3 py-2 bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded-lg transition-all"
              >
                <Edit className="w-4 h-4" />
                Edit
              </button>
            </div>
          </div>
        ))}
      </div>

      {filteredRoles.length === 0 && (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-12 text-center border border-white/20">
          <Shield className="w-16 h-16 text-white/30 mx-auto mb-4" />
          <p className="text-white/50">No roles found</p>
        </div>
      )}

      {/* Role Details Modal */}
      {selectedRole && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4" onClick={() => setSelectedRole(null)}>
          <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 max-w-2xl w-full max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="p-6">
              <div className="flex items-start justify-between mb-6">
                <div>
                  <h2 className="text-2xl font-bold text-white mb-2">
                    {selectedRole.displayName || selectedRole.name.replace(/_/g, ' ')}
                  </h2>
                  <p className="text-white/70">{selectedRole.description}</p>
                </div>
                <button onClick={() => setSelectedRole(null)} className="text-white/70 hover:text-white">
                  ✕
                </button>
              </div>

              <div className="space-y-6">
                {/* Basic Info */}
                <div>
                  <h3 className="text-white font-semibold mb-3">Basic Information</h3>
                  <div className="bg-white/5 rounded-lg p-4 space-y-2">
                    <div className="flex justify-between">
                      <span className="text-white/70">Role Name:</span>
                      <span className="text-white font-medium">{selectedRole.name}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-white/70">Level:</span>
                      <span className="text-white font-medium">{selectedRole.level} - {getLevelName(selectedRole.level)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-white/70">Status:</span>
                      <span className={selectedRole.isActive ? 'text-green-400' : 'text-gray-400'}>
                        {selectedRole.isActive ? 'Active' : 'Inactive'}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Permissions */}
                {selectedRole.permissions && selectedRole.permissions.length > 0 && (
                  <div>
                    <h3 className="text-white font-semibold mb-3">
                      Permissions ({selectedRole.permissions.length})
                    </h3>
                    <div className="bg-white/5 rounded-lg p-4">
                      <div className="flex flex-wrap gap-2">
                        {selectedRole.permissions.map((perm, idx) => (
                          <span key={idx} className="px-3 py-1 bg-primary/20 text-primary text-sm rounded">
                            {perm.replace(/_/g, ' ').toLowerCase()}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                )}

                {/* Capabilities */}
                {selectedRole.capabilities && selectedRole.capabilities.length > 0 && (
                  <div>
                    <h3 className="text-white font-semibold mb-3">
                      Capabilities ({selectedRole.capabilities.length})
                    </h3>
                    <div className="bg-white/5 rounded-lg p-4">
                      <div className="flex flex-wrap gap-2">
                        {selectedRole.capabilities.map((cap, idx) => (
                          <span key={idx} className="px-3 py-1 bg-blue-500/20 text-blue-400 text-sm rounded">
                            {cap.replace(/_/g, ' ').toLowerCase()}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="mt-6 pt-6 border-t border-white/10">
                <button
                  onClick={() => setSelectedRole(null)}
                  className="w-full px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
