import TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";
import { FormDrawerShell } from "@/shared/ui/FormDrawerShell.jsx";
import { RolePermissionEditor } from "@/features/roles/components/RolePermissionEditor.jsx";

export function RoleFormDrawer({
  abilities,
  editingRole,
  form,
  onClose,
  onSubmit,
  onTogglePermissionGroup,
  onTogglePermission,
  open,
  permissionGroups,
  setForm
}) {
  const [activeSection, setActiveSection] = useState("profile");

  useEffect(() => {
    // 新开角色表单时先展示身份字段，避免沿用上一角色的权限分类上下文。
    if (open) {
      setActiveSection("profile");
    }
  }, [editingRole, open]);

  return (
    <FormDrawerShell
      activeSection={activeSection}
      className="role-form-workspace"
      onClose={onClose}
      onSectionChange={setActiveSection}
      onSubmit={onSubmit}
      open={open}
      sections={[
        { key: "profile", label: "基础信息" },
        ...(abilities.canLoadPermissions
          ? [{ count: form.permissionIds.length, key: "permissions", label: "权限配置" }]
          : [])
      ]}
      summary={editingRole ? `角色编码：${form.code}` : "新增后台角色"}
      title={editingRole ? "编辑角色" : "新增角色"}
    >
      {activeSection === "profile" ? (
        <section className="form-drawer__section form-drawer__panel">
          <div className="form-drawer__section-title">基础信息</div>
          <div className="form-drawer__grid">
            <TextField disabled={editingRole ? !abilities.canUpdate : !abilities.canCreate} label="角色名称" required value={form.name} onChange={(event) => setForm({ ...form, name: event.target.value })} />
            <TextField disabled={editingRole ? !abilities.canUpdate : !abilities.canCreate} label="角色编码" required value={form.code} onChange={(event) => setForm({ ...form, code: event.target.value })} />
            <TextField disabled={editingRole ? !abilities.canUpdate : !abilities.canCreate} label="说明" value={form.description} onChange={(event) => setForm({ ...form, description: event.target.value })} />
          </div>
        </section>
      ) : null}

      {activeSection === "permissions" && abilities.canLoadPermissions ? (
        <RolePermissionEditor
          abilities={abilities}
          onTogglePermission={onTogglePermission}
          onTogglePermissionGroup={onTogglePermissionGroup}
          permissionGroups={permissionGroups}
          permissionIds={form.permissionIds}
        />
      ) : null}
    </FormDrawerShell>
  );
}
