import SearchOutlined from "@mui/icons-material/SearchOutlined";
import Checkbox from "@mui/material/Checkbox";
import InputAdornment from "@mui/material/InputAdornment";
import TextField from "@mui/material/TextField";
import { useEffect, useMemo, useState } from "react";

export function RolePermissionEditor({
    abilities,
    onTogglePermission,
    onTogglePermissionGroup,
    permissionGroups,
    permissionIds,
}) {
    const [activeGroupKey, setActiveGroupKey] = useState("");
    const [query, setQuery] = useState("");
    const [selectedOnly, setSelectedOnly] = useState(false);

    const visibleGroups = useMemo(() => {
        const keyword = query.trim().toLowerCase();
        // 全局搜索先收窄分类再展示命中项，权限 ID 集合不随筛选变化，避免隐藏项被意外清空。
        return permissionGroups
            .map((group) => ({
                ...group,
                visibleItems: group.items.filter((permission) => {
                    if (selectedOnly && !permissionIds.includes(permission.id)) {
                        return false;
                    }
                    return (
                        !keyword ||
                        [permission.name, permission.code].some((value) =>
                            String(value || "")
                                .toLowerCase()
                                .includes(keyword),
                        )
                    );
                }),
            }))
            .filter((group) => group.visibleItems.length > 0 || (!query && !selectedOnly));
    }, [permissionGroups, permissionIds, query, selectedOnly]);

    useEffect(() => {
        // 当前分类被搜索条件过滤掉时定位首个命中分类，让右侧始终对应左侧可见导航。
        if (!visibleGroups.some((group) => group.key === activeGroupKey)) {
            setActiveGroupKey(visibleGroups[0]?.key || "");
        }
    }, [activeGroupKey, visibleGroups]);

    const activeGroup = visibleGroups.find((group) => group.key === activeGroupKey) || visibleGroups[0];

    return (
        <div className="form-editor-split form-editor-split--permissions">
            <nav aria-label="权限分类" className="form-editor-rail">
                <div className="form-editor-rail__label">权限分类</div>
                {visibleGroups.map((group) => {
                    const selectedCount = countSelected(group.items, permissionIds);
                    return (
                        <button
                            aria-current={group.key === activeGroup?.key ? "page" : undefined}
                            className={group.key === activeGroup?.key ? "is-active" : ""}
                            key={group.key}
                            onClick={() => setActiveGroupKey(group.key)}
                            type="button"
                        >
                            <span>{group.title}</span>
                            <span className="form-editor-rail__count">
                                {selectedCount}/{group.items.length}
                            </span>
                        </button>
                    );
                })}
            </nav>

            <section className="form-editor-panel" aria-label={activeGroup ? `${activeGroup.title}权限` : "权限"}>
                <div className="form-editor-toolbar form-editor-toolbar--permissions">
                    <div>
                        <strong>{activeGroup?.title || "权限范围"}</strong>
                        <span>
                            已选 {permissionIds.length} / {permissionGroups.reduce((total, group) => total + group.items.length, 0)} 项
                        </span>
                    </div>
                    <TextField
                        aria-label="搜索权限"
                        onChange={(event) => setQuery(event.target.value)}
                        placeholder="搜索权限名称或编码"
                        slotProps={{
                            input: {
                                startAdornment: (
                                    <InputAdornment position="start">
                                        <SearchOutlined fontSize="small" />
                                    </InputAdornment>
                                ),
                            },
                        }}
                        value={query}
                    />
                    <label className="form-editor-filter">
                        <Checkbox checked={selectedOnly} onChange={(event) => setSelectedOnly(event.target.checked)} size="small" />
                        <span>仅看已选</span>
                    </label>
                </div>

                {activeGroup ? (
                    <>
                        <div className="form-editor-group-actions">
                            <span>{activeGroup.visibleItems.length} 项</span>
                            <label>
                                <Checkbox
                                    checked={countSelected(activeGroup.items, permissionIds) === activeGroup.items.length}
                                    disabled={!abilities.canGrant}
                                    indeterminate={
                                        countSelected(activeGroup.items, permissionIds) > 0 &&
                                        countSelected(activeGroup.items, permissionIds) < activeGroup.items.length
                                    }
                                    onChange={(event) => onTogglePermissionGroup(activeGroup.items.map((item) => item.id), event.target.checked)}
                                    size="small"
                                />
                                <span>全选本组</span>
                            </label>
                        </div>
                        <div className="form-option-grid form-option-grid--permissions">
                            {activeGroup.visibleItems.map((permission) => (
                                <label className="form-option" key={permission.id} title={permission.code}>
                                    <Checkbox
                                        checked={permissionIds.includes(permission.id)}
                                        disabled={!abilities.canGrant}
                                        onChange={(event) => onTogglePermission(permission.id, event.target.checked)}
                                        size="small"
                                    />
                                    <span>
                                        <strong>{permission.name}</strong>
                                        <small>{permission.code}</small>
                                    </span>
                                </label>
                            ))}
                        </div>
                    </>
                ) : (
                    <div className="form-editor-state">当前无匹配权限</div>
                )}
            </section>
        </div>
    );
}

function countSelected(items, permissionIds) {
    return items.filter((permission) => permissionIds.includes(permission.id)).length;
}
