import React, { useState, useCallback, } from "react";
import Card from "../Card/Card";
import IconProp from "../../../Types/Icon/IconProp";
import ObjectID from "../../../Types/ObjectID";
import API from "../../Utils/API/API";
import ComponentLoader from "../ComponentLoader/ComponentLoader";
import ErrorMessage from "../ErrorMessage/ErrorMessage";
import Image from "../Image/Image";
import Route from "../../../Types/API/Route";
import Icon from "../Icon/Icon";
import ConfirmModal from "../Modal/ConfirmModal";
import Modal from "../Modal/Modal";
import Dropdown from "../Dropdown/Dropdown";
import { ButtonStyleType } from "../Button/Button";
const MemberRoleAssignment = (props) => {
    const [isAssigning, setIsAssigning] = useState(false);
    const [isUnassigning, setIsUnassigning] = useState(null);
    const [showConfirmDelete, setShowConfirmDelete] = useState(null);
    const [activeRoleDropdown, setActiveRoleDropdown] = useState(null);
    const [selectedUserOption, setSelectedUserOption] = useState(null);
    const [localError, setLocalError] = useState("");
    const [reassignState, setReassignState] = useState(null);
    const [isReassigning, setIsReassigning] = useState(false);
    const handleAssign = useCallback(async (userId, roleId) => {
        try {
            setIsAssigning(true);
            setLocalError("");
            await props.onAssignMember(userId, roleId);
            setActiveRoleDropdown(null);
            setSelectedUserOption(null);
        }
        catch (err) {
            setLocalError(API.getFriendlyMessage(err));
        }
        finally {
            setIsAssigning(false);
        }
    }, [props.onAssignMember]);
    const handleUnassign = useCallback(async (member) => {
        try {
            setIsUnassigning(member.memberId);
            setLocalError("");
            await props.onUnassignMember(member.memberId);
            setShowConfirmDelete(null);
        }
        catch (err) {
            setLocalError(API.getFriendlyMessage(err));
        }
        finally {
            setIsUnassigning(null);
        }
    }, [props.onUnassignMember]);
    const handleReassign = useCallback(async (currentMember, newUserId, roleId) => {
        try {
            setIsReassigning(true);
            setLocalError("");
            // First unassign the current member
            await props.onUnassignMember(currentMember.memberId);
            // Then assign the new user
            await props.onAssignMember(newUserId, roleId);
            setReassignState(null);
            setSelectedUserOption(null);
        }
        catch (err) {
            setLocalError(API.getFriendlyMessage(err));
        }
        finally {
            setIsReassigning(false);
        }
    }, [props.onUnassignMember, props.onAssignMember]);
    // Get members for a specific role
    const getMembersForRole = useCallback((roleId) => {
        return props.assignedMembers.filter((member) => {
            return member.roleId.toString() === roleId.toString();
        });
    }, [props.assignedMembers]);
    // Get available users for a role (excluding already assigned users for that role)
    const getAvailableUsersForRole = useCallback((roleId) => {
        const assignedUserIds = new Set(getMembersForRole(roleId).map((m) => {
            return m.userId.toString();
        }));
        return props.availableUsers
            .filter((user) => {
            return !assignedUserIds.has(user.id.toString());
        })
            .map((user) => {
            return {
                value: user.id.toString(),
                label: user.name || user.email,
            };
        });
    }, [props.availableUsers, getMembersForRole]);
    const cardTitle = props.title || "Team Members";
    const cardDescription = props.description || "Manage team member role assignments.";
    if (props.isLoading) {
        return (React.createElement(Card, { title: cardTitle, description: cardDescription, className: props.className },
            React.createElement(ComponentLoader, null)));
    }
    if (props.error) {
        return (React.createElement(Card, { title: cardTitle, description: cardDescription, className: props.className },
            React.createElement(ErrorMessage, { message: props.error })));
    }
    // Render a single member row
    const renderMemberRow = (member, role, isLastInGroup) => {
        var _a, _b, _c, _d;
        const isPrimaryRole = role.isPrimaryRole || false;
        return (React.createElement("div", { key: member.memberId.toString(), className: `flex items-center justify-between py-2 ${!isLastInGroup ? "border-b border-gray-100" : ""}` },
            React.createElement("div", { className: "flex items-center gap-3" },
                member.userProfilePictureUrl ? (React.createElement(Image, { imageUrl: Route.fromString(member.userProfilePictureUrl), alt: member.userName, className: "h-8 w-8 rounded-full object-cover" })) : (React.createElement("div", { className: "h-8 w-8 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center" },
                    React.createElement("span", { className: "text-xs font-medium text-white" }, ((_b = (_a = member.userName) === null || _a === void 0 ? void 0 : _a.charAt(0)) === null || _b === void 0 ? void 0 : _b.toUpperCase()) ||
                        ((_d = (_c = member.userEmail) === null || _c === void 0 ? void 0 : _c.charAt(0)) === null || _d === void 0 ? void 0 : _d.toUpperCase()) ||
                        "?"))),
                React.createElement("div", { className: "min-w-0" },
                    React.createElement("p", { className: "text-sm font-medium text-gray-900 truncate" }, member.userName || member.userEmail),
                    member.userName && member.userEmail && (React.createElement("p", { className: "text-xs text-gray-500 truncate" }, member.userEmail)))),
            isPrimaryRole ? (React.createElement("button", { type: "button", onClick: () => {
                    setReassignState({ member, role });
                }, className: "inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-indigo-600 hover:text-indigo-800 hover:bg-indigo-50 rounded-md transition-colors", title: "Reassign" },
                React.createElement(Icon, { icon: IconProp.ArrowCircleRight, className: "w-3.5 h-3.5" }),
                "Reassign")) : (React.createElement("button", { type: "button", onClick: () => {
                    setShowConfirmDelete(member);
                }, disabled: (isUnassigning === null || isUnassigning === void 0 ? void 0 : isUnassigning.toString()) === member.memberId.toString(), className: "inline-flex items-center p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors disabled:opacity-50", title: "Remove" }, (isUnassigning === null || isUnassigning === void 0 ? void 0 : isUnassigning.toString()) === member.memberId.toString() ? (React.createElement(Icon, { icon: IconProp.Refresh, className: "w-4 h-4 animate-spin" })) : (React.createElement(Icon, { icon: IconProp.Close, className: "w-4 h-4" }))))));
    };
    return (React.createElement(React.Fragment, null,
        React.createElement(Card, { title: cardTitle, description: cardDescription, className: props.className, buttons: props.onRefresh
                ? [
                    {
                        title: "Refresh",
                        icon: IconProp.Refresh,
                        onClick: () => {
                            var _a;
                            (_a = props.onRefresh) === null || _a === void 0 ? void 0 : _a.call(props);
                        },
                        buttonStyle: ButtonStyleType.OUTLINE,
                    },
                ]
                : [] },
            React.createElement("div", null,
                localError && (React.createElement("div", { className: "mb-4" },
                    React.createElement(ErrorMessage, { message: localError }))),
                props.roles.length === 0 ? (React.createElement("div", { className: "text-center py-12" },
                    React.createElement(Icon, { icon: IconProp.User, className: "mx-auto h-12 w-12 text-gray-300" }),
                    React.createElement("h3", { className: "mt-2 text-sm font-medium text-gray-900" }, "No roles defined"),
                    React.createElement("p", { className: "mt-1 text-sm text-gray-500" }, props.emptyStateMessage ||
                        "Configure roles in settings to start assigning team members."))) : (React.createElement("div", { className: "space-y-4" }, props.roles.map((role) => {
                    var _a;
                    const members = getMembersForRole(role.id);
                    const isDropdownActive = (activeRoleDropdown === null || activeRoleDropdown === void 0 ? void 0 : activeRoleDropdown.toString()) === role.id.toString();
                    const availableUsers = getAvailableUsersForRole(role.id);
                    const canAddMore = role.canAssignMultipleUsers || members.length === 0;
                    return (React.createElement("div", { key: role.id.toString(), className: "border border-gray-200 rounded-lg overflow-hidden" },
                        React.createElement("div", { className: "px-4 py-3 flex items-center justify-between", style: {
                                backgroundColor: role.color
                                    ? `${role.color.toString()}10`
                                    : "#f9fafb",
                            } },
                            React.createElement("div", { className: "flex items-center gap-3" },
                                React.createElement("div", { className: "w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0", style: {
                                        backgroundColor: role.color
                                            ? `${role.color.toString()}25`
                                            : "#e5e7eb",
                                    } },
                                    React.createElement(Icon, { icon: role.icon || IconProp.User, className: "w-5 h-5", style: {
                                            color: ((_a = role.color) === null || _a === void 0 ? void 0 : _a.toString()) || "#6b7280",
                                        } })),
                                React.createElement("div", null,
                                    React.createElement("div", { className: "flex items-center gap-2" },
                                        React.createElement("span", { className: "text-sm font-semibold text-gray-900" }, role.name),
                                        role.isPrimaryRole && (React.createElement("span", { className: "inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-800" }, "Primary")),
                                        role.canAssignMultipleUsers && (React.createElement("span", { className: "inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700" }, "Multiple"))),
                                    React.createElement("p", { className: "text-xs text-gray-500 mt-0.5" },
                                        members.length,
                                        " ",
                                        members.length === 1 ? "member" : "members",
                                        " ",
                                        "assigned"))),
                            !isDropdownActive && canAddMore && (React.createElement("button", { type: "button", onClick: () => {
                                    setActiveRoleDropdown(role.id);
                                }, className: "inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-all shadow-sm text-gray-700 bg-white border border-gray-300 hover:bg-gray-50 hover:border-gray-400" },
                                React.createElement(Icon, { icon: IconProp.Add, className: "w-3.5 h-3.5" }),
                                members.length === 0 ? "Assign" : "Add More"))),
                        isDropdownActive && (React.createElement("div", { className: "px-4 py-3 bg-gray-50 border-b border-gray-200" }, availableUsers.length === 0 ? (React.createElement("div", { className: "flex items-center justify-between" },
                            React.createElement("p", { className: "text-sm text-red-600" }, "All users are already assigned to this role."),
                            React.createElement("button", { type: "button", onClick: () => {
                                    setActiveRoleDropdown(null);
                                    setSelectedUserOption(null);
                                }, className: "inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors" }, "Close"))) : (React.createElement("div", { className: "flex items-center gap-2" },
                            React.createElement("div", { className: "flex-1 max-w-sm" },
                                React.createElement(Dropdown, { options: availableUsers, placeholder: "Select member...", onChange: (value) => {
                                        if (value && !Array.isArray(value)) {
                                            const option = availableUsers.find((opt) => {
                                                return (opt.value.toString() ===
                                                    value.toString());
                                            });
                                            setSelectedUserOption(option || null);
                                        }
                                        else {
                                            setSelectedUserOption(null);
                                        }
                                    }, value: selectedUserOption || undefined })),
                            React.createElement("button", { type: "button", onClick: () => {
                                    if (selectedUserOption) {
                                        handleAssign(new ObjectID(selectedUserOption.value.toString()), role.id);
                                    }
                                }, disabled: !selectedUserOption || isAssigning, className: "inline-flex items-center px-3 py-1.5 text-xs font-medium text-white bg-indigo-600 border border-transparent rounded-md hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" }, isAssigning ? (React.createElement(Icon, { icon: IconProp.Refresh, className: "w-3.5 h-3.5 animate-spin" })) : ("Save")),
                            React.createElement("button", { type: "button", onClick: () => {
                                    setActiveRoleDropdown(null);
                                    setSelectedUserOption(null);
                                }, className: "inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors" }, "Cancel"))))),
                        React.createElement("div", { className: "px-4 py-2 bg-white" }, members.length === 0 ? (React.createElement("p", { className: "text-sm text-gray-400 italic py-2" }, "Not assigned")) : (members.map((member, index) => {
                            return renderMemberRow(member, role, index === members.length - 1);
                        })))));
                }))))),
        showConfirmDelete && (React.createElement(ConfirmModal, { title: "Remove Member", description: `Are you sure you want to remove ${showConfirmDelete.userName || showConfirmDelete.userEmail} from the ${showConfirmDelete.roleName} role?`, submitButtonText: "Remove", submitButtonType: ButtonStyleType.DANGER, onSubmit: () => {
                handleUnassign(showConfirmDelete);
            }, onClose: () => {
                setShowConfirmDelete(null);
            } })),
        reassignState && (React.createElement(Modal, { title: "Reassign Role", submitButtonText: isReassigning ? "Reassigning..." : "Reassign", submitButtonStyleType: ButtonStyleType.PRIMARY, onSubmit: () => {
                if (selectedUserOption) {
                    handleReassign(reassignState.member, new ObjectID(selectedUserOption.value.toString()), reassignState.role.id);
                }
            }, disableSubmitButton: !selectedUserOption || isReassigning, onClose: () => {
                setReassignState(null);
                setSelectedUserOption(null);
            } },
            React.createElement("p", { className: "text-gray-500 text-sm mb-4" },
                "Select a new user to reassign the ",
                reassignState.role.name,
                " role from",
                " ",
                reassignState.member.userName || reassignState.member.userEmail,
                "."),
            React.createElement(Dropdown, { options: props.availableUsers
                    .filter((user) => {
                    // Exclude the current member from the list
                    return (user.id.toString() !== reassignState.member.userId.toString());
                })
                    .map((user) => {
                    return {
                        value: user.id.toString(),
                        label: user.name || user.email,
                    };
                }), placeholder: "Select new user...", onChange: (value) => {
                    if (value && !Array.isArray(value)) {
                        const option = props.availableUsers
                            .map((user) => {
                            return {
                                value: user.id.toString(),
                                label: user.name || user.email,
                            };
                        })
                            .find((opt) => {
                            return opt.value.toString() === value.toString();
                        });
                        setSelectedUserOption(option || null);
                    }
                    else {
                        setSelectedUserOption(null);
                    }
                }, value: selectedUserOption || undefined })))));
};
export default MemberRoleAssignment;
//# sourceMappingURL=MemberRoleAssignment.js.map