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";
import { AppIdentity } from "@/shared/ui/AppIdentity.jsx";

export function UserFinanceScopeEditor({ assignments = [], catalog, checkedScopes, excludeUserId, onChecked }) {
    const apps = useMemo(() => catalog?.apps || [], [catalog?.apps]);
    const [activeAppCode, setActiveAppCode] = useState("");
    const [query, setQuery] = useState("");
    const [selectedOnly, setSelectedOnly] = useState(false);
    const [unassignedOnly, setUnassignedOnly] = useState(false);

    useEffect(() => {
        // 目录刷新后主动回退到第一个有效应用，防止权限变化导致右侧仍引用已移除的应用。
        if (!apps.some((app) => app.appCode === activeAppCode)) {
            setActiveAppCode(apps[0]?.appCode || "");
        }
    }, [activeAppCode, apps]);

    // 他人（排除当前编辑对象）的持有关系：区域粒度置灰 + 持有人标注，让"剩下哪些区没分"一眼可见。
    const holderIndex = useMemo(() => buildHolderIndex(assignments, excludeUserId), [assignments, excludeUserId]);

    const activeApp = apps.find((app) => app.appCode === activeAppCode) || apps[0];
    const appRegions = useMemo(
        () => (catalog?.regions || []).filter((region) => region.appCode === activeApp?.appCode),
        [activeApp?.appCode, catalog?.regions],
    );

    const allRegionsChecked = activeApp ? hasScope(checkedScopes, activeApp.appCode, 0) : false;

    const appStats = useMemo(() => {
        if (!activeApp) {
            return { taken: 0, unassigned: 0 };
        }
        let taken = 0;
        let unassigned = 0;
        for (const region of appRegions) {
            if (holdersFor(holderIndex, activeApp.appCode, region.regionId).length) {
                taken += 1;
            } else if (!allRegionsChecked && !hasScope(checkedScopes, activeApp.appCode, region.regionId)) {
                unassigned += 1;
            }
        }
        return { taken, unassigned };
    }, [activeApp, allRegionsChecked, appRegions, checkedScopes, holderIndex]);

    const activeRegions = useMemo(() => {
        const keyword = query.trim().toLowerCase();
        // 搜索与筛选只影响展示集合，原始勾选状态始终保留，切换应用或筛选不会丢失授权。
        return appRegions.filter((region) => {
            const checked = hasScope(checkedScopes, activeApp?.appCode, region.regionId);
            if (selectedOnly && !checked) {
                return false;
            }
            if (unassignedOnly && (checked || holdersFor(holderIndex, activeApp?.appCode, region.regionId).length)) {
                return false;
            }
            return !keyword || [region.name, region.regionCode].some((value) => String(value || "").toLowerCase().includes(keyword));
        });
    }, [activeApp?.appCode, appRegions, checkedScopes, holderIndex, query, selectedOnly, unassignedOnly]);

    if (catalog?.loading) {
        return <div className="form-editor-state">加载中</div>;
    }
    if (catalog?.error) {
        return <div className="form-editor-state form-editor-state--error">{catalog.error}</div>;
    }
    if (!apps.length) {
        return <div className="form-editor-state">当前无数据</div>;
    }

    const allHolders = holdersFor(holderIndex, activeApp.appCode, 0);
    const appTakenByOthers = appStats.taken > 0 || allHolders.length > 0;

    return (
        <div className="form-editor-split form-editor-split--finance">
            <nav aria-label="应用范围" className="form-editor-rail">
                <div className="form-editor-rail__label">应用</div>
                {apps.map((app) => {
                    const selectedCount = countAppScopes(checkedScopes, app.appCode);
                    return (
                        <button
                            aria-current={app.appCode === activeApp.appCode ? "page" : undefined}
                            className={app.appCode === activeApp.appCode ? "is-active" : ""}
                            key={app.appCode}
                            onClick={() => {
                                setActiveAppCode(app.appCode);
                                setQuery("");
                            }}
                            type="button"
                        >
                            <AppIdentity app={app} size="small" />
                            <span className="form-editor-rail__count">{selectedCount}</span>
                        </button>
                    );
                })}
            </nav>

            <section className="form-editor-panel" aria-label={`${activeApp.appName || activeApp.appCode}财务范围`}>
                <div className="form-editor-toolbar">
                    <div>
                        <strong>{activeApp.appName || activeApp.appCode}</strong>
                        <span>
                            已选 {countAppScopes(checkedScopes, activeApp.appCode)} 项 · 他人已分 {appStats.taken} · 未分配 {appStats.unassigned}
                        </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);
                                if (event.target.checked) {
                                    setUnassignedOnly(false);
                                }
                            }}
                            size="small"
                        />
                        <span>仅看已选</span>
                    </label>
                    <label className="form-editor-filter">
                        <Checkbox
                            checked={unassignedOnly}
                            onChange={(event) => {
                                setUnassignedOnly(event.target.checked);
                                if (event.target.checked) {
                                    setSelectedOnly(false);
                                }
                            }}
                            size="small"
                        />
                        <span>仅看未分配</span>
                    </label>
                </div>

                <div className="form-option-grid form-option-grid--finance">
                    {(!selectedOnly || allRegionsChecked) && !unassignedOnly && !query ? (
                        <FinanceScopeOption
                            checked={allRegionsChecked}
                            code="ALL"
                            // 他人已占任一区域时不允许再整包全选，避免和已有分工重叠。
                            disabled={!allRegionsChecked && appTakenByOthers}
                            holderText={
                                allHolders.length
                                    ? `已分配：${holderNames(allHolders)}`
                                    : appStats.taken > 0
                                        ? `他人已分 ${appStats.taken} 区`
                                        : ""
                            }
                            label="全部区域"
                            onChange={(checked) => onChecked(activeApp.appCode, 0, checked)}
                        />
                    ) : null}
                    {activeRegions.map((region) => {
                        const holders = holdersFor(holderIndex, activeApp.appCode, region.regionId);
                        const checked = hasScope(checkedScopes, activeApp.appCode, region.regionId);
                        return (
                            <FinanceScopeOption
                                checked={checked}
                                code={region.regionCode}
                                disabled={!checked && holders.length > 0}
                                holderText={holders.length ? `已分配：${holderNames(holders)}` : ""}
                                key={region.regionId}
                                label={region.name}
                                onChange={(nextChecked) => onChecked(activeApp.appCode, region.regionId, nextChecked)}
                            />
                        );
                    })}
                </div>
                {!activeRegions.length && (query || selectedOnly || unassignedOnly) && !(selectedOnly && allRegionsChecked) ? (
                    <div className="form-editor-state">当前无匹配区域</div>
                ) : null}
            </section>
        </div>
    );
}

function FinanceScopeOption({ checked, code, disabled = false, holderText = "", label, onChange }) {
    return (
        <label className={`form-option${disabled ? " form-option--disabled" : ""}`}>
            <Checkbox checked={checked} disabled={disabled} onChange={(event) => onChange(event.target.checked)} size="small" />
            <span>
                <strong>{label}</strong>
                {code ? <small>{code}</small> : null}
                {holderText ? <small className="form-option__holder">{holderText}</small> : null}
            </span>
        </label>
    );
}

function scopeKey(appCode, regionId) {
    return `${String(appCode || "").trim().toLowerCase()}:${Number(regionId || 0)}`;
}

function buildHolderIndex(assignments, excludeUserId) {
    const index = new Map();
    for (const item of Array.isArray(assignments) ? assignments : []) {
        if (excludeUserId != null && Number(item.userId) === Number(excludeUserId)) {
            continue;
        }
        const key = scopeKey(item.appCode, item.regionId);
        const holders = index.get(key) || [];
        if (!holders.some((holder) => Number(holder.userId) === Number(item.userId))) {
            holders.push({ name: String(item.userName || item.userAccount || `用户${item.userId}`), userId: item.userId });
        }
        index.set(key, holders);
    }
    return index;
}

function holdersFor(index, appCode, regionId) {
    const exact = index.get(scopeKey(appCode, regionId)) || [];
    if (Number(regionId || 0) === 0) {
        return exact;
    }
    // 持有"全部区域"的人视为占有该 App 下每个区域。
    const holdAll = index.get(scopeKey(appCode, 0)) || [];
    if (!holdAll.length) {
        return exact;
    }
    const merged = [...exact];
    for (const holder of holdAll) {
        if (!merged.some((existing) => Number(existing.userId) === Number(holder.userId))) {
            merged.push(holder);
        }
    }
    return merged;
}

function holderNames(holders) {
    const names = holders.map((holder) => holder.name);
    if (names.length > 2) {
        return `${names.slice(0, 2).join("、")} 等${names.length}人`;
    }
    return names.join("、");
}

function hasScope(scopes, appCode, regionId) {
    return (scopes || []).some(
        (scope) => scope.appCode === appCode && Number(scope.regionId) === Number(regionId),
    );
}

function countAppScopes(scopes, appCode) {
    return (scopes || []).filter((scope) => scope.appCode === appCode).length;
}
