import Drawer from "@mui/material/Drawer";
import MenuItem from "@mui/material/MenuItem";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import TextField from "@mui/material/TextField";
import { Button } from "@/shared/ui/Button.jsx";

export function UserFormDrawer({
  editingUser,
  financeScopeCatalog,
  form,
  onClose,
  onFinanceScopeChecked,
  onRoleChecked,
  onSubmit,
  open,
  roles,
  setForm,
  teams = []
}) {
  return (
    <Drawer anchor="right" open={open} onClose={onClose}>
      <form className="form-drawer form-drawer--sticky-actions" onSubmit={onSubmit}>
        <h2>{editingUser ? "编辑用户" : "新增用户"}</h2>
        <div className="form-drawer__content">
          <section className="form-drawer__section">
            <div className="form-drawer__section-title">基础信息</div>
            <div className="form-drawer__grid">
              <TextField
                disabled={Boolean(editingUser)}
                label="账号"
                required
                value={form.username}
                onChange={(event) => setForm({ ...form, username: event.target.value })}
              />
              <TextField label="姓名" required value={form.name} onChange={(event) => setForm({ ...form, name: event.target.value })} />
              <TextField
                label="团队"
                select
                value={form.teamId ?? ""}
                onChange={(event) => {
                  const teamId = event.target.value;
                  const team = teams.find((item) => String(item.id) === String(teamId));
                  setForm({ ...form, team: team?.name || "", teamId });
                }}
              >
                <MenuItem value="">未选择</MenuItem>
                {teams.map((team) => (
                  <MenuItem key={team.id} value={team.id}>
                    {team.parentName ? `${team.parentName} / ${team.name}` : team.name}
                  </MenuItem>
                ))}
              </TextField>
              {!editingUser ? (
                <TextField label="初始密码" type="password" value={form.password} onChange={(event) => setForm({ ...form, password: event.target.value })} />
              ) : null}
            </div>
          </section>
          <section className="form-drawer__section">
            <div className="form-drawer__section-title">财务范围</div>
            <div className="permission-grid permission-grid--finance">
              {financeScopeCatalog?.loading ? <span className="permission-check">加载中</span> : null}
              {financeScopeCatalog?.error ? <span className="permission-check">{financeScopeCatalog.error}</span> : null}
              {!financeScopeCatalog?.loading && !financeScopeCatalog?.error
                ? (financeScopeCatalog?.apps || []).map((app) => (
                    <FinanceScopeGroup
                      app={app}
                      checkedScopes={form.financeScopes || []}
                      key={app.appCode}
                      onChecked={onFinanceScopeChecked}
                      regions={(financeScopeCatalog?.regions || []).filter((region) => region.appCode === app.appCode)}
                    />
                  ))
                : null}
            </div>
          </section>
          <section className="form-drawer__section">
            <div className="form-drawer__section-title">角色</div>
            <div className="permission-grid">
              {roles.map((role) => (
                <label className="permission-check" key={role.id}>
                  <input
                    checked={form.roleIds.includes(role.id)}
                    onChange={(event) => onRoleChecked(role.id, event.target.checked)}
                    type="checkbox"
                  />
                  <span>{role.name}</span>
                </label>
              ))}
            </div>
          </section>
          <section className="form-drawer__section">
            <div className="form-drawer__section-title">安全设置</div>
            <AdminSwitch
              checked={form.mfaEnabled}
              checkedLabel="开启"
              label="MFA 状态"
              uncheckedLabel="关闭"
              onChange={(event) => setForm({ ...form, mfaEnabled: event.target.checked })}
            />
          </section>
        </div>
        <div className="form-drawer__actions">
          <Button onClick={onClose}>取消</Button>
          <Button type="submit" variant="primary">提交</Button>
        </div>
      </form>
    </Drawer>
  );
}

function FinanceScopeGroup({ app, checkedScopes, onChecked, regions }) {
  const appCode = app.appCode;
  const isChecked = (regionId) =>
    checkedScopes.some((scope) => scope.appCode === appCode && Number(scope.regionId) === Number(regionId));

  return (
    <div className="permission-scope-group">
      <strong>{app.appName || appCode}</strong>
      <label className="permission-check" key={`${appCode}:0`}>
        <input checked={isChecked(0)} onChange={(event) => onChecked(appCode, 0, event.target.checked)} type="checkbox" />
        <span>全部区域</span>
      </label>
      {regions.map((region) => (
        <label className="permission-check" key={`${appCode}:${region.regionId}`}>
          <input
            checked={isChecked(region.regionId)}
            onChange={(event) => onChecked(appCode, region.regionId, event.target.checked)}
            type="checkbox"
          />
          <span>{[region.name, region.regionCode].filter(Boolean).join(" · ")}</span>
        </label>
      ))}
    </div>
  );
}
