import Checkbox from "@mui/material/Checkbox";
import { AppIdentity } from "@/shared/ui/AppIdentity.jsx";

export function UserAppScopeEditor({ apps = [], appCodes = [], mode = "none", onAppChecked, onModeChange }) {
  const selected = new Set((appCodes || []).map(normalizeAppCode));
  const all = mode === "all";
  const count = all ? apps.length : selected.size;

  if (!apps.length) {
    return <div className="form-editor-state">当前无数据</div>;
  }

  return (
    <section className="form-drawer__panel form-drawer__section" aria-label="App 可见范围">
      <div className="form-drawer__section-heading">
        <div className="form-drawer__section-title">App 可见范围</div>
        <span>已选 {count} 项</span>
      </div>
      <div className="form-option-grid form-option-grid--roles">
        <label className="form-option form-option--single-line">
          <Checkbox checked={all} onChange={(event) => onModeChange(event.target.checked ? "all" : "none")} size="small" />
          <span>全部 App</span>
        </label>
        {apps.map((app) => {
          const appCode = normalizeAppCode(app.appCode);
          return (
            <label className="form-option form-option--single-line" key={appCode}>
              <Checkbox checked={all || selected.has(appCode)} onChange={(event) => onAppChecked(appCode, event.target.checked)} size="small" />
              <AppIdentity app={app} size="small" />
            </label>
          );
        })}
      </div>
    </section>
  );
}

function normalizeAppCode(value) {
  return String(value || "").trim().toLowerCase();
}
