import React, { useEffect, useState } from "react";
import { getUser, patchUser, getAllRole } from "@/services/userService";
import { toast } from "react-toastify";
import "./ChangeRoleModal.css";
import CustomSelect from "../../common/CustomSelect";

export default function ChangeRoleModal({ show, onClose, userId }) {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const [roles, setRoles] = useState([]);
    const [selectedRole, setSelectedRole] = useState("");
    const [currentRole, setCurrentRole] = useState("");

    useEffect(() => {
        if (show && userId) loadData();
    }, [show, userId]);

    const loadData = async () => {
        try {
            setLoading(true);

            const roleRes = await getAllRole();
            setRoles(roleRes.data || []);

            const { data } = await getUser(userId);
            const roleId = data.roles?.[0] || "";

            const matchedRole = roleRes.data.find((r) => r.id === roleId);

            setSelectedRole(roleId);
            setCurrentRole(matchedRole ? matchedRole.name : roleId);
        } catch (err) {
            toast.error("Failed to load role data");
        } finally {
            setLoading(false);
        }
    };


    const saveRole = async () => {
        try {
            setSaving(true);
            await patchUser(userId, { roles: [selectedRole] });

            toast.success("Role updated successfully");
            onClose();
        } catch (err) {
            toast.error("Failed to update role");
        } finally {
            setSaving(false);
        }
    };

    if (!show) return null;

    return (
        <div className="custom-modal-overlay">
            <div className="custom-modal">
                {/* Header */}
                <div className="modal-header-custom">
                    <h2 className="modal-title-custom">Change User Role</h2>
                    <button className="close-btn-custom" onClick={onClose}>×</button>
                </div>

                {/* Body */}
                <div className="modal-body-custom">
                    {loading ? (
                        <p>Loading...</p>
                    ) : (
                        <>
                            <div className="label-block">
                                <p className="label-title">Current Role</p>
                                <span className="role-pill">{currentRole}</span>
                                <p className="label-subtext">
                                    Lead analyst with case management capabilities
                                </p>
                            </div>

                            <div className="label-block mt-20">
                                <CustomSelect
                                    name="role"
                                    value={selectedRole}
                                    placeholder="Select user role"
                                    options={roles.map((role) => ({
                                        value: role.id,
                                        label: role.name,
                                    }))}
                                    onChange={(e) => setSelectedRole(e.target.value)}
                                />


                                <p className="info-text">
                                    Changing a user’s role will immediately update their permissions
                                    and access levels throughout the system.
                                </p>
                            </div>
                        </>
                    )}
                </div>

                {/* Footer */}
                <div className="modal-footer-custom">
                    <button className="btn-cancel" onClick={onClose} disabled={saving}>
                        Cancel
                    </button>

                    <button className="btn-save" onClick={saveRole} disabled={saving}>
                        {saving ? "Saving..." : "Save Changes"}
                    </button>
                </div>
            </div>
        </div>
    );
}
