import React, { useEffect, useRef, useState } from 'react';
import { AccountDetailRespond, Api, RoleModel } from '../../client/auth_client';
import './EditRolesModal.css';

interface EditRolesModalProps {
    user: AccountDetailRespond;
    availableRoles: RoleModel[];
    closeModal: () => void;
}

const EditRolesModal: React.FC<EditRolesModalProps> = ({ user, availableRoles, closeModal }) => {
    const [userRoles, setUserRoles] = useState<string[]>([]);
    const [roleSearchQuery, setRoleSearchQuery] = useState<string>('');
    const [filteredRoles, setFilteredRoles] = useState<RoleModel[]>(availableRoles);
    const [showDropdown, setShowDropdown] = useState<boolean>(false);
    const [loadingRoles, setLoadingRoles] = useState<boolean>(true);
    const modalRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const getRoles = async () => {
            const token = localStorage.getItem("authToken");
            const client = new Api({
                baseUrl: "/auth",
                securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
            });

            try {
                let result = await client.role.getUserRolesCreate({ userIdentify: user.id });
                if (result && result.data.roles) {
                    const roles = result.data.roles
                        .map((role) => role.roleName)
                        .filter((roleName): roleName is string => roleName != null); // Filter null or undefined values
                    setUserRoles(roles);
                }
            } catch (e) {
                console.error('Error fetching user roles:', e);
            } finally {
                setLoadingRoles(false);
            }
        };

        getRoles().then();
    }, [user.id]);

    useEffect(() => {
        setFilteredRoles(availableRoles);
    }, [availableRoles]);

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') {
                closeModal();
            }
        };

        const handleClickOutside = (e: MouseEvent) => {
            if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
                closeModal();
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        document.addEventListener('mousedown', handleClickOutside);

        return () => {
            document.removeEventListener('keydown', handleKeyDown);
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [closeModal]);

    const handleRoleSearch = (query: string) => {
        setRoleSearchQuery(query);
        setFilteredRoles(
            availableRoles.filter((role) =>
                role.roleName?.toLowerCase().includes(query.toLowerCase())
            )
        );
        setShowDropdown(query.length > 0);
    };

    const handleAddRole = (role: string) => {
        if (!userRoles.includes(role)) {
            setUserRoles([...userRoles, role]);
        }
        setRoleSearchQuery('');
        setShowDropdown(false);
    };

    const handleRemoveRole = (role: string) => {
        setUserRoles(userRoles.filter((r) => r !== role));
    };

    return (
        <div className="edit-roles-window">
            <div className="edit-roles-content" ref={modalRef}>
                <h3>Edit Roles for {user.userName}</h3>
                {loadingRoles ? (
                    <div className="loading-screen">
                        <div className="spinner">
                            <div className="lds-ring">
                                <div></div>
                                <div></div>
                                <div></div>
                                <div></div>
                            </div>
                        </div>
                    </div>
                ) : (
                    <>
                        <div className="role-search">
                            <h4>Available Roles</h4>
                            <div className="role-search-container">
                                <input
                                    type="text"
                                    placeholder="Search roles..."
                                    value={roleSearchQuery}
                                    onChange={(e) => handleRoleSearch(e.target.value)}
                                    className="form-control role-search-input"
                                />
                                {showDropdown && (
                                    <div className="role-dropdown">
                                        {filteredRoles.length > 0 ? (
                                            filteredRoles.map((role) => (
                                                <div
                                                    key={role.roleName}
                                                    className="role-dropdown-item"
                                                    onClick={() => handleAddRole(role.roleName ?? "")}
                                                >
                                                    {role.roleName}
                                                </div>
                                            ))
                                        ) : (
                                            <div className="role-dropdown-item">No roles found</div>
                                        )}
                                    </div>
                                )}
                            </div>
                        </div>
                        <div className="assigned-roles">
                            <h4>Assigned Roles</h4>
                            {userRoles.length > 0 ? (
                                <ul>
                                    {userRoles.map((role) => (
                                        <li key={role}>
                                            {role}
                                            <button
                                                className="btn-remove-role"
                                                onClick={() => handleRemoveRole(role)}
                                            >
                                                Remove
                                            </button>
                                        </li>
                                    ))}
                                </ul>
                            ) : (
                                <p>No roles assigned</p>
                            )}
                        </div>
                        <div className="edit-roles-actions">
                            <button className="btn-save" onClick={() => alert('Roles updated successfully!')}>
                                Save
                            </button>
                            <button className="btn-cancel" onClick={closeModal}>
                                Cancel
                            </button>
                        </div>
                    </>
                )}
            </div>
        </div>
    );
};

export default EditRolesModal;
