import React, { useState, useEffect } from 'react';
import { 
    Plus, MagnifyingGlass, Trash, PencilSimple,
    ShieldCheck, UserGear, Lock, LockOpen,
    CheckCircle, XCircle, Users, ArrowRight
} from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';

export default function RoleManagement() {
    const [roles, setRoles] = useState([]);
    const [permissions, setPermissions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [editingRole, setEditingRole] = useState(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [user, setUser] = useState(null);
    const [users, setUsers] = useState([]);
    const [activeTab, setActiveTab] = useState('roles');
    const [assigningRole, setAssigningRole] = useState(null);

    const [formData, setFormData] = useState({
        name: '',
        description: '',
        permissions: [],
        company_id: null,
    });

    useEffect(() => {
        fetchUser();
        fetchRoles();
        fetchPermissions();
    }, []);

    const fetchUser = async () => {
        try {
            const response = await axios.get('/api/me');
            setUser(response.data);
        } catch (error) {
            console.error('Error fetching user:', error);
        }
    };

    const fetchRoles = async () => {
        try {
            setLoading(true);
            const response = await axios.get('/api/roles');
            setRoles(response.data.data);
        } catch (error) {
            console.error('Error fetching roles:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchPermissions = async () => {
        try {
            const response = await axios.get('/api/permissions');
            setPermissions(response.data.data);
        } catch (error) {
            console.error('Error fetching permissions:', error);
        }
    };

    const fetchUsers = async () => {
        try {
            const response = await axios.get('/api/employees?per_page=100');
            setUsers(response.data.data || []);
        } catch (error) {
            console.error('Error fetching users:', error);
        }
    };

    const handleAssignRole = async (targetUserId, roleId) => {
        try {
            await axios.post('/api/roles/assign', { user_id: targetUserId, role_id: roleId });
            toast.success('Role assigned successfully');
            fetchUsers();
        } catch (error) {
            console.error('Error assigning role:', error);
            toast.error(error.response?.data?.message || 'Failed to assign role');
        }
    };

    const handleRevokeRole = async (targetUserId, roleId) => {
        try {
            await axios.post('/api/roles/revoke', { user_id: targetUserId, role_id: roleId });
            toast.success('Role revoked successfully');
            fetchUsers();
        } catch (error) {
            console.error('Error revoking role:', error);
            toast.error(error.response?.data?.message || 'Failed to revoke role');
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            if (editingRole) {
                await axios.put(`/api/roles/${editingRole.id}`, formData);
            } else {
                await axios.post('/api/roles', formData);
            }
            setShowModal(false);
            resetForm();
            fetchRoles();
        } catch (error) {
            console.error('Error saving role:', error);
            alert(error.response?.data?.message || 'Error saving role');
        }
    };

    const handleDelete = async (roleId) => {
        if (!confirm('Are you sure you want to delete this role?')) return;
        
        try {
            await axios.delete(`/api/roles/${roleId}`);
            fetchRoles();
        } catch (error) {
            console.error('Error deleting role:', error);
            alert(error.response?.data?.message || 'Error deleting role');
        }
    };

    const resetForm = () => {
        setFormData({
            name: '',
            description: '',
            permissions: [],
            company_id: user?.company_id || null,
        });
        setEditingRole(null);
    };

    const openEditModal = (role) => {
        setEditingRole(role);
        setFormData({
            name: role.name,
            description: role.description || '',
            permissions: role.permissions?.map(p => p.id) || [],
            company_id: role.company_id,
        });
        setShowModal(true);
    };

    const togglePermission = (permissionId) => {
        setFormData(prev => ({
            ...prev,
            permissions: prev.permissions.includes(permissionId)
                ? prev.permissions.filter(id => id !== permissionId)
                : [...prev.permissions, permissionId]
        }));
    };

    const filteredRoles = roles.filter(role =>
        role.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        role.description?.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const isSuperAdmin = user?.roles?.some(r => r.name === 'Super Admin');
    const canManageGlobalRoles = isSuperAdmin;

    // Group permissions by category
    const groupedPermissions = permissions.reduce((acc, perm) => {
        const category = perm.name.split('.')[0] || 'other';
        if (!acc[category]) acc[category] = [];
        acc[category].push(perm);
        return acc;
    }, {});

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-6">
            {/* Header */}
            <div className="mb-8">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2 flex items-center gap-3">
                            <ShieldCheck size={36} weight="duotone" className="text-primary-600" />
                            Role Management
                        </h1>
                        <p className="text-gray-600">
                            {canManageGlobalRoles 
                                ? 'Manage roles and permissions across all companies' 
                                : 'Manage roles for your company'}
                        </p>
                    </div>
                    <div className="flex items-center gap-3">
                        <div className="flex bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                            <button
                                onClick={() => setActiveTab('roles')}
                                className={`px-4 py-2 text-sm font-medium transition-colors ${activeTab === 'roles' ? 'bg-primary-600 text-white' : 'text-gray-700 hover:bg-gray-50'}`}
                            >
                                <ShieldCheck size={16} className="inline mr-1" />
                                Roles
                            </button>
                            <button
                                onClick={() => { setActiveTab('assignment'); fetchUsers(); }}
                                className={`px-4 py-2 text-sm font-medium transition-colors ${activeTab === 'assignment' ? 'bg-primary-600 text-white' : 'text-gray-700 hover:bg-gray-50'}`}
                            >
                                <Users size={16} className="inline mr-1" />
                                User Assignment
                            </button>
                        </div>
                        {activeTab === 'roles' && (
                            <button
                                onClick={() => {
                                    resetForm();
                                    setShowModal(true);
                                }}
                                className="flex items-center gap-2 px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors shadow-lg"
                            >
                                <Plus size={20} weight="bold" />
                                Create Role
                            </button>
                        )}
                    </div>
                </div>
            </div>

            {/* Search Bar */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-6">
                <div className="relative">
                    <MagnifyingGlass size={20} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                    <input
                        type="text"
                        placeholder="Search roles..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                    />
                </div>
            </div>

            {/* Tab Content */}
            {activeTab === 'roles' ? (
            <>
            {/* Roles Grid */}
            {loading ? (
                <div className="flex items-center justify-center py-12">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
                </div>
            ) : (
                <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 rounded-xl shadow-sm border border-gray-100 p-6 hover:shadow-md transition-all duration-200">
                            <div className="flex items-start justify-between mb-4">
                                <div className="flex-1">
                                    <div className="flex items-center gap-2 mb-2">
                                        <UserGear size={24} weight="duotone" className="text-primary-600" />
                                        <h3 className="text-lg font-bold text-gray-900">{role.name}</h3>
                                    </div>
                                    {role.description && (
                                        <p className="text-sm text-gray-600 mb-3">{role.description}</p>
                                    )}
                                    <div className="flex items-center gap-2 text-xs">
                                        {role.company_id ? (
                                            <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded-md font-medium">
                                                Company Role
                                            </span>
                                        ) : (
                                            <span className="px-2 py-1 bg-primary-100 text-primary-700 rounded-md font-medium">
                                                Global Role
                                            </span>
                                        )}
                                        <span className="text-gray-500">
                                            {role.users_count || 0} users
                                        </span>
                                    </div>
                                </div>
                                {(!role.company_id && !canManageGlobalRoles) ? null : (
                                    <div className="flex gap-2">
                                        <button
                                            onClick={() => openEditModal(role)}
                                            className="p-2 text-primary-600 hover:bg-primary-50 rounded-lg transition-colors"
                                        >
                                            <PencilSimple size={18} weight="bold" />
                                        </button>
                                        {role.name !== 'Super Admin' && (
                                            <button
                                                onClick={() => handleDelete(role.id)}
                                                className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                            >
                                                <Trash size={18} weight="bold" />
                                            </button>
                                        )}
                                    </div>
                                )}
                            </div>

                            {/* Permissions Preview */}
                            <div className="mt-4 pt-4 border-t border-gray-100">
                                <div className="text-xs font-semibold text-gray-500 mb-2">PERMISSIONS ({role.permissions?.length || 0})</div>
                                <div className="flex flex-wrap gap-1">
                                    {(role.permissions || []).slice(0, 4).map((perm, idx) => (
                                        <span key={idx} className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded-md">
                                            {perm.name.split('.').pop()}
                                        </span>
                                    ))}
                                    {role.permissions?.length > 4 && (
                                        <span className="px-2 py-1 bg-gray-200 text-gray-600 text-xs rounded-md">
                                            +{role.permissions.length - 4} more
                                        </span>
                                    )}
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
            </>
            ) : (
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <div className="flex items-center justify-between mb-4">
                    <h3 className="text-lg font-bold text-gray-900">User Role Assignment</h3>
                    <span className="text-sm text-gray-500">{users.length} users found</span>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                        <thead className="bg-gray-50 text-gray-700 font-semibold">
                            <tr>
                                <th className="px-4 py-3 text-left">User</th>
                                <th className="px-4 py-3 text-left">Email</th>
                                <th className="px-4 py-3 text-left">Current Roles</th>
                                <th className="px-4 py-3 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                            {users.map(u => (
                                <tr key={u.id} className="hover:bg-gray-50">
                                    <td className="px-4 py-3 font-medium text-gray-900">{u.first_name} {u.last_name}</td>
                                    <td className="px-4 py-3 text-gray-500">{u.email}</td>
                                    <td className="px-4 py-3">
                                        <div className="flex flex-wrap gap-1">
                                            {(u.roles || []).map((r, idx) => (
                                                <span key={idx} className="px-2 py-0.5 bg-primary-100 text-primary-700 text-xs rounded-md">{r.name}</span>
                                            ))}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="flex gap-2">
                                            {roles.filter(r => r.company_id === user?.company_id || !r.company_id).map(role => (
                                                <button
                                                    key={role.id}
                                                    onClick={() => handleAssignRole(u.id, role.id)}
                                                    className="px-2 py-1 text-xs bg-primary-600 text-white rounded hover:bg-primary-700 transition-colors"
                                                >
                                                    + {role.name}
                                                </button>
                                            ))}
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
            )}

            {/* Create/Edit Modal */}
            {showModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
                        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4">
                            <h2 className="text-2xl font-bold text-gray-900">
                                {editingRole ? 'Edit Role' : 'Create New Role'}
                            </h2>
                        </div>

                        <form onSubmit={handleSubmit} className="p-6">
                            {/* Role Name */}
                            <div className="mb-6">
                                <label className="block text-sm font-semibold text-gray-700 mb-2">
                                    Role Name *
                                </label>
                                <input
                                    type="text"
                                    required
                                    value={formData.name}
                                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    placeholder="e.g., Finance Manager"
                                />
                            </div>

                            {/* Description */}
                            <div className="mb-6">
                                <label className="block text-sm font-semibold text-gray-700 mb-2">
                                    Description
                                </label>
                                <textarea
                                    value={formData.description}
                                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                    rows="3"
                                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                    placeholder="Brief description of this role..."
                                />
                            </div>

                            {/* Permissions */}
                            <div className="mb-6">
                                <label className="block text-sm font-semibold text-gray-700 mb-3">
                                    Permissions
                                </label>
                                <div className="space-y-4">
                                    {Object.entries(groupedPermissions).map(([category, perms]) => (
                                        <div key={category} className="border border-gray-200 rounded-lg p-4">
                                            <div className="font-semibold text-gray-900 mb-3 capitalize flex items-center gap-2">
                                                <Lock size={18} className="text-gray-500" />
                                                {category}
                                            </div>
                                            <div className="grid grid-cols-2 gap-3">
                                                {perms.map(perm => (
                                                    <label key={perm.id} className="flex items-center gap-2 cursor-pointer group">
                                                        <input
                                                            type="checkbox"
                                                            checked={formData.permissions.includes(perm.id)}
                                                            onChange={() => togglePermission(perm.id)}
                                                            className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
                                                        />
                                                        <span className="text-sm text-gray-700 group-hover:text-gray-900">
                                                            {perm.name.split('.').pop()}
                                                        </span>
                                                    </label>
                                                ))}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Actions */}
                            <div className="flex gap-3 justify-end pt-4 border-t border-gray-200">
                                <button
                                    type="button"
                                    onClick={() => {
                                        setShowModal(false);
                                        resetForm();
                                    }}
                                    className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    className="px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors"
                                >
                                    {editingRole ? 'Update Role' : 'Create Role'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
