import React, { useEffect, useRef, useState } from 'react';
import {Api as Auth, RoleModel} from '../../client/auth_client';
import PhoneInputComponent from "./PhoneInputComponent.tsx";

interface CreateUserModalProps {
    closeModal: () => void;
    availableRoles: RoleModel[];
    refreshList: () => void;
}

const CreateUserModal: React.FC<CreateUserModalProps> = ({ closeModal, availableRoles, refreshList }) => {
    const [newUser, setNewUser] = useState({
        userName: '',
        email: '',
        password: '',
        confirmPassword: '',
    });

    const [dialCode, setDialCode] = useState<string | null>();
    const [phoneNumber, setPhoneNumber] = useState<string |null>();

    const [userRoles, setUserRoles] = useState<string[]>([]);
    const [roleSearchQuery, setRoleSearchQuery] = useState<string>('');
    const [filteredRoles, setFilteredRoles] = useState<RoleModel[]>([]);
    const [showDropdown, setShowDropdown] = useState<boolean>(false);
    const modalRef = useRef<HTMLDivElement>(null);
    const [loading, setLoading] = useState<boolean>(false);
    const [successMessage, setSuccessMessage] = useState<string | null>(null);

    useEffect(() => {
        // Initialize filtered roles to be the available roles (excluding already chosen roles)
        setFilteredRoles(filterAvailableRoles());
    }, [availableRoles, userRoles]);

    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 filterAvailableRoles = () => {
        return availableRoles.filter((role) => !userRoles.includes(role.roleName ?? ""));
    };

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

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

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

    const handleCreateUser = async () => {
        setLoading(true); // Start loading
        const token = localStorage.getItem("authToken");
        const client = new Auth({
            baseUrl: "/auth",
            securityWorker: () => ({ headers: { Authorization: `Bearer ${token}` } }),
        });

        try {
            const result = await client.account.createUserCreate({
                email: newUser.email,
                password: newUser.password,
                roles: userRoles,
                username: newUser.userName,
                dialcode: dialCode,
                phone: phoneNumber,
            });

            if (result.status === 200) {
                refreshList()
                setSuccessMessage("User created successfully!");
                setTimeout(() => {
                    setSuccessMessage(null);
                    closeModal();
                }, 2000);
            } else {
                alert("Failed to create user. Please try again.");
            }
        } catch (error) {
            console.error("Error creating user:", error);
            alert("Failed to create user. Please try again.");
        } finally {
            setLoading(false); // Stop loading
        }
    };

    return (
        <div className="edit-user-window">
            <div className="edit-user-content" ref={modalRef}>
                <h3>Create User</h3>
                {successMessage && <div className="success-message">{successMessage}</div>}
                <label>
                    Name:
                    <input
                        type="text"
                        value={newUser.userName}
                        onChange={(e) => setNewUser({ ...newUser, userName: e.target.value })}
                        className="form-control"
                    />
                </label>
                <label>
                    Email:
                    <input
                        type="email"
                        value={newUser.email}
                        onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
                        className="form-control"
                    />
                </label>
                <label>
                    Phone:
                    <PhoneInputComponent value={`${dialCode}${phoneNumber}`}
                                         onChange={ (phone, data) =>{
                                             let lenOfDialCode : number = 0;
                                             if ("dialCode" in data) {
                                                 lenOfDialCode = data.dialCode.length;
                                                 setDialCode(data.dialCode);
                                             }

                                             const phoneNumber = phone.slice(lenOfDialCode, phone.length);

                                             setPhoneNumber(phoneNumber);

                                         }}/>
                </label>
                <label>
                    Password:
                    <input
                        type="password"
                        value={newUser.password}
                        onChange={(e) => setNewUser({ ...newUser, password: e.target.value })}
                        className="form-control"
                    />
                </label>
                <label>
                    Confirm Password:
                    <input
                        type="password"
                        value={newUser.confirmPassword}
                        onChange={(e) => setNewUser({ ...newUser, confirmPassword: e.target.value })}
                        className="form-control"
                    />
                </label>
                <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">
                                <div className="role-list">
                                    {filteredRoles.map((role) => (
                                        <div
                                            key={role.roleName}
                                            className="role-dropdown-item"
                                            onClick={() => handleAddRole(role.roleName ?? "")}
                                        >
                                            {role.roleName}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
                <div className="assigned-roles">
                    <h4>Assigned Roles</h4>
                    <ul>
                        {userRoles.map((role) => (
                            <li key={role}>
                                {role}
                                <button
                                    className="btn-remove-role"
                                    onClick={() => handleRemoveRole(role)}
                                >
                                    Remove
                                </button>
                            </li>
                        ))}
                    </ul>
                </div>
                <div className="edit-user-actions">
                    <button
                        className="btn-save"
                        onClick={handleCreateUser}
                        disabled={(loading || successMessage != null)}
                    >
                        {loading && (<span className="spinner-border spinner-border-sm" role="status"
                                           aria-hidden="true"></span>)}
                        Create
                    </button>
                    <button className="btn-cancel" onClick={closeModal}>Cancel</button>
                </div>
            </div>
        </div>
    );
};

export default CreateUserModal;
