import Checkbox from "@mui/material/Checkbox";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { FormDrawerShell } from "@/shared/ui/FormDrawerShell.jsx";
import { UserFinanceScopeEditor } from "@/features/users/components/UserFinanceScopeEditor.jsx";
import { UserAppScopeEditor } from "@/features/users/components/UserAppScopeEditor.jsx";

export function UserFormDrawer({
  editingUser,
  appScopeCatalog = [],
  financeScopeAssignments = [],
  financeScopeCatalog,
  form,
  onClose,
  onFinanceScopeChecked,
  onAppScopeChecked,
  onAppScopeModeChange,
  onRoleChecked,
  onSubmit,
  open,
  roles,
  setForm,
  teams = []
}) {
  const [activeSection, setActiveSection] = useState("profile");

  useEffect(() => {
    // 每次切换编辑对象都回到账号资料，避免复用抽屉时停留在上一位用户的授权页造成误操作。
    if (open) {
      setActiveSection("profile");
    }
  }, [editingUser, open]);

  const sections = [
    { key: "profile", label: "账号资料" },
    { count: form.financeScopes?.length || 0, key: "finance", label: "财务范围" },
    { count: form.roleIds?.length || 0, key: "access", label: "角色与安全" },
    { count: form.appScopeMode === "all" ? appScopeCatalog.length : form.appCodes?.length || 0, key: "apps", label: "App范围" }
  ];

  return (
    <FormDrawerShell
      activeSection={activeSection}
      className="user-form-workspace"
      onClose={onClose}
      onSectionChange={setActiveSection}
      onSubmit={onSubmit}
      open={open}
      sections={sections}
      summary={editingUser ? `账号：${form.username}` : "新增后台用户"}
      title={editingUser ? "编辑用户" : "新增用户"}
    >
      {activeSection === "profile" ? (
        <section className="form-drawer__section form-drawer__panel">
          <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>
      ) : null}

      {activeSection === "finance" ? (
        <UserFinanceScopeEditor
          assignments={financeScopeAssignments}
          catalog={financeScopeCatalog}
          checkedScopes={form.financeScopes || []}
          excludeUserId={editingUser?.id}
          onChecked={onFinanceScopeChecked}
        />
      ) : null}

      {activeSection === "access" ? (
        <div className="form-drawer__panel form-drawer__access-panel">
          <section className="form-drawer__section">
            <div className="form-drawer__section-heading">
              <div className="form-drawer__section-title">角色</div>
              <span>已选 {form.roleIds.length} 项</span>
            </div>
            <div className="form-option-grid form-option-grid--roles">
              {roles.map((role) => (
                <label className="form-option form-option--single-line" key={role.id}>
                  <Checkbox
                    checked={form.roleIds.includes(role.id)}
                    onChange={(event) => onRoleChecked(role.id, event.target.checked)}
                    size="small"
                  />
                  <span>{role.name}</span>
                </label>
              ))}
            </div>
          </section>
          <section className="form-drawer__section">
            <div className="form-drawer__section-title">安全设置</div>
            <div className="form-setting-row">
              <div>
                <strong>MFA 状态</strong>
                <span>登录时进行多因素认证</span>
              </div>
              <AdminSwitch
                checked={form.mfaEnabled}
                checkedLabel="开启"
                label="MFA 状态"
                uncheckedLabel="关闭"
                onChange={(event) => setForm({ ...form, mfaEnabled: event.target.checked })}
              />
            </div>
          </section>
        </div>
      ) : null}

      {activeSection === "apps" ? (
        <UserAppScopeEditor
          apps={appScopeCatalog}
          appCodes={form.appCodes || []}
          mode={form.appScopeMode}
          onAppChecked={onAppScopeChecked}
          onModeChange={onAppScopeModeChange}
        />
      ) : null}
    </FormDrawerShell>
  );
}
