'use client';

import { useEffect, useMemo, useState } from 'react';
import { Plus, Pencil, Trash2, X, ChevronRight, FolderOpen, Settings, Search } from 'lucide-react';
import { useMemberStore } from '@/stores/useMemberStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { generatePassword, generateUsernameFromName } from '@/lib/members';
import type { Member, Department, PasswordRule } from '@/lib/members';
import { isSystemAdminMember } from '@/lib/member-system';
import { filterMembersForList, getDisplayedAccountPassword, resolveLatestEditingMember } from '@/lib/member-list';
import { RouteGuard } from '@/components/auth/Guard';

export default function MembersPage() {
  return (
    <RouteGuard permission="member:view">
      <MembersPageContent />
    </RouteGuard>
  );
}

function MembersPageContent() {
  const { departments, members, roles, passwordRule, fetchMembers, updatePasswordRule, createDepartment, updateDepartment, deleteDepartment, createMember, updateMember, deleteMember } = useMemberStore();
  const currentUser = useAuthStore((s) => s.user);
  const refreshUser = useAuthStore((s) => s.refreshUser);
  const [activeDeptId, setActiveDeptId] = useState<string | null>(null);
  const [nameKeyword, setNameKeyword] = useState('');
  const [showMemberModal, setShowMemberModal] = useState(false);
  const [editingMember, setEditingMember] = useState<Member | null>(null);
  const [showDeptModal, setShowDeptModal] = useState(false);
  const [editingDept, setEditingDept] = useState<Department | null>(null);
  const [expandedDepts, setExpandedDepts] = useState<Set<string>>(new Set(['dept-2']));
  const [showPwdRuleModal, setShowPwdRuleModal] = useState(false);

  useEffect(() => { fetchMembers(); }, [fetchMembers]);

  const topDepts = useMemo(() => departments.filter((d) => !d.parentId).sort((a, b) => a.order - b.order), [departments]);
  const childDepts = (parentId: string) => departments.filter((d) => d.parentId === parentId).sort((a, b) => a.order - b.order);

  const filteredMembers = useMemo(() => {
    return filterMembersForList({ members, departments, activeDeptId, nameKeyword });
  }, [members, departments, activeDeptId, nameKeyword]);
  const latestEditingMember = useMemo(
    () => resolveLatestEditingMember(editingMember, members),
    [editingMember, members],
  );

  const activeDeptName = activeDeptId ? departments.find((d) => d.id === activeDeptId)?.name ?? '全部' : '全部成员';
  const roleName = (roleId: string) => roles.find((r) => r.id === roleId)?.name ?? '-';

  const toggleExpand = (id: string) => {
    setExpandedDepts((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  };

  return (
    <div className="flex h-full">
      {/* Left: Departments */}
      <div className="w-[220px] shrink-0 border-r border-[var(--line)] bg-[var(--bg-card)] flex flex-col">
        <div className="flex items-center justify-between px-4 py-3 border-b border-[var(--line)]">
          <span className="text-[13px] font-semibold text-[var(--ink)]">部门</span>
          <button onClick={() => { setEditingDept(null); setShowDeptModal(true); }} className="p-1 rounded-md hover:bg-[var(--bg-subtle)] text-[var(--ink-muted)] hover:text-[var(--accent)]">
            <Plus className="h-3.5 w-3.5" />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto py-1">
          {/* All */}
          <button
            onClick={() => setActiveDeptId(null)}
            className={`w-full flex items-center gap-2 px-4 py-2 text-[12px] transition-colors ${!activeDeptId ? 'bg-[var(--accent-soft)] text-[var(--accent)] font-medium' : 'text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]'}`}
          >
            <FolderOpen className="h-3.5 w-3.5" />
            全部成员
            <span className="ml-auto text-[11px] tabular-nums text-[var(--ink-muted)]">{members.length}</span>
          </button>
          {/* Tree */}
          {topDepts.map((dept) => {
            const children = childDepts(dept.id);
            const expanded = expandedDepts.has(dept.id);
            const count = members.filter((m) => m.departmentId === dept.id || children.some((c) => c.id === m.departmentId)).length;
            return (
              <div key={dept.id}>
                <div className={`group flex items-center px-4 py-2 text-[12px] cursor-pointer transition-colors ${activeDeptId === dept.id ? 'bg-[var(--accent-soft)] text-[var(--accent)] font-medium' : 'text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]'}`}>
                  {children.length > 0 && (
                    <button onClick={() => toggleExpand(dept.id)} className="p-0.5 mr-1 rounded hover:bg-[var(--bg-card)]">
                      <ChevronRight className={`h-3 w-3 transition-transform ${expanded ? 'rotate-90' : ''}`} />
                    </button>
                  )}
                  {children.length === 0 && <span className="w-4" />}
                  <span onClick={() => setActiveDeptId(dept.id)} className="flex-1">{dept.name}</span>
                  <span className="text-[11px] tabular-nums text-[var(--ink-muted)]">{count}</span>
                  <div className="hidden group-hover:flex items-center ml-1 gap-0.5">
                    <button onClick={(e) => { e.stopPropagation(); setEditingDept(dept); setShowDeptModal(true); }} className="p-0.5 rounded hover:bg-[var(--bg-card)] text-[var(--ink-muted)]">
                      <Pencil className="h-3 w-3" />
                    </button>
                    <button onClick={(e) => { e.stopPropagation(); deleteDepartment(dept.id); if (activeDeptId === dept.id) setActiveDeptId(null); }} className="p-0.5 rounded hover:bg-[var(--bg-card)] text-[var(--ink-muted)] hover:text-red-500">
                      <Trash2 className="h-3 w-3" />
                    </button>
                  </div>
                </div>
                {expanded && children.map((child) => {
                  const childCount = members.filter((m) => m.departmentId === child.id).length;
                  return (
                    <div
                      key={child.id}
                      onClick={() => setActiveDeptId(child.id)}
                      className={`group flex items-center pl-9 pr-4 py-2 text-[12px] cursor-pointer transition-colors ${activeDeptId === child.id ? 'bg-[var(--accent-soft)] text-[var(--accent)] font-medium' : 'text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]'}`}
                    >
                      <span className="flex-1">{child.name}</span>
                      <span className="text-[11px] tabular-nums text-[var(--ink-muted)]">{childCount}</span>
                      <div className="hidden group-hover:flex items-center ml-1 gap-0.5">
                        <button onClick={(e) => { e.stopPropagation(); setEditingDept(child); setShowDeptModal(true); }} className="p-0.5 rounded hover:bg-[var(--bg-card)] text-[var(--ink-muted)]">
                          <Pencil className="h-3 w-3" />
                        </button>
                        <button onClick={(e) => { e.stopPropagation(); deleteDepartment(child.id); if (activeDeptId === child.id) setActiveDeptId(null); }} className="p-0.5 rounded hover:bg-[var(--bg-card)] text-[var(--ink-muted)] hover:text-red-500">
                          <Trash2 className="h-3 w-3" />
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>

      {/* Right: Member list */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <header className="flex h-14 shrink-0 items-center justify-between border-b border-[var(--line)] bg-[var(--bg-card)] px-5">
          <div className="flex items-center gap-2.5">
            <h2 className="text-[14px] font-semibold text-[var(--ink)]">{activeDeptName}</h2>
            <span className="rounded-md bg-[var(--bg-subtle)] px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-[var(--ink-soft)]">{filteredMembers.length}</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="relative">
              <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-[var(--ink-muted)]" />
              <input
                value={nameKeyword}
                onChange={(e) => setNameKeyword(e.target.value)}
                placeholder="搜索姓名"
                className="h-8 w-44 rounded-lg border border-[var(--line)] bg-[var(--bg)] pl-8 pr-3 text-[13px] text-[var(--ink)] placeholder:text-[var(--ink-muted)] focus:border-[var(--accent)] focus:outline-none"
              />
            </div>
            <button onClick={() => setShowPwdRuleModal(true)} className="flex h-8 items-center gap-1.5 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] font-medium text-[var(--ink-soft)] hover:border-[var(--accent)] hover:text-[var(--accent)] transition-colors">
              <Settings className="h-3.5 w-3.5" strokeWidth={2} />
              账号密码设置
            </button>
            <button onClick={() => { setEditingMember(null); setShowMemberModal(true); }} className="flex h-8 items-center gap-1.5 rounded-lg bg-[var(--accent)] px-3 text-[13px] font-medium text-white shadow-[var(--shadow-sm)] hover:bg-[var(--accent-hover)] transition-colors">
              <Plus className="h-3.5 w-3.5" strokeWidth={2} />
              新建成员
            </button>
          </div>
        </header>

        <div className="flex-1 overflow-hidden bg-[var(--bg)] px-5 py-4">
          {filteredMembers.length === 0 ? (
            <div className="rounded-2xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] py-20 text-center">
              <p className="text-[13px] font-medium text-[var(--ink-soft)]">暂无成员</p>
            </div>
          ) : (
            <div className="h-full overflow-hidden rounded-2xl border border-[var(--line)] bg-[var(--bg-card)] shadow-[var(--shadow-sm)]">
              <div className="h-full overflow-y-auto">
                <table className="w-full text-left text-[13px]">
                  <thead className="bg-[var(--bg-subtle)]">
                    <tr className="bg-[var(--bg-subtle)]">
                      <th className="sticky top-0 z-20 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-4 py-2.5 text-[11px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">姓名</th>
                      <th className="sticky top-0 z-20 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-4 py-2.5 text-[11px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">用户名</th>
                      <th className="sticky top-0 z-20 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-4 py-2.5 text-[11px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">角色</th>
                      <th className="sticky top-0 z-20 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-4 py-2.5 text-[11px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">部门</th>
                      <th className="sticky top-0 z-20 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-4 py-2.5 text-[11px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">企业邮箱</th>
                      <th className="sticky top-0 z-20 border-b border-[var(--line)] bg-[var(--bg-subtle)] px-4 py-2.5 text-right text-[11px] font-medium uppercase tracking-wide text-[var(--ink-muted)]">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredMembers.map((m) => (
                      <tr key={m.id} className="border-b border-[var(--line-soft)] last:border-0 hover:bg-[var(--bg-subtle)] transition-colors">
                        <td className="px-4 py-3 font-medium text-[var(--ink)]">{m.name}</td>
                        <td className="px-4 py-3 font-mono text-[var(--ink-soft)]">{m.username ?? '-'}</td>
                        <td className="px-4 py-3">
                          <span className="inline-flex items-center rounded-md bg-[var(--bg-subtle)] px-2 py-0.5 text-[11px] font-medium text-[var(--ink-soft)]">{roleName(m.roleId)}</span>
                        </td>
                        <td className="px-4 py-3 text-[var(--ink-soft)]">{departments.find((d) => d.id === m.departmentId)?.name ?? '-'}</td>
                        <td className="px-4 py-3 text-[var(--ink-soft)]">{m.email}</td>
                        <td className="px-4 py-3 text-right">
                          <div className="flex items-center justify-end gap-1">
                            <button onClick={() => { setEditingMember(m); setShowMemberModal(true); }} className="h-6 px-2 rounded text-[11px] font-medium text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]">编辑</button>
                            {!isSystemAdminMember(m) && (
                              <button onClick={() => deleteMember(m.id)} className="h-6 px-2 rounded text-[11px] font-medium text-red-500 hover:bg-red-50">删除</button>
                            )}
                            {isSystemAdminMember(m) && (
                              <span className="h-6 px-2 inline-flex items-center rounded text-[11px] font-medium text-amber-700 bg-amber-50">系统账号</span>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Member Modal */}
      {showMemberModal && (
        <MemberModal
          initial={latestEditingMember}
          departments={departments}
          roles={roles}
          existingUsernames={members.map((m) => m.username ?? '')}
          defaultDeptId={activeDeptId}
          passwordRule={passwordRule}
          onClose={() => setShowMemberModal(false)}
          onSubmit={(data) => {
            if (editingMember) {
              updateMember(editingMember.id, data);
              if (editingMember.id === currentUser?.id) void refreshUser();
            } else {
              createMember(data as any);
            }
            setShowMemberModal(false);
          }}
        />
      )}

      {/* Department Modal */}
      {showDeptModal && (
        <DeptModal
          initial={editingDept}
          departments={departments}
          onClose={() => setShowDeptModal(false)}
          onSubmit={(data) => {
            if (editingDept) updateDepartment(editingDept.id, data);
            else createDepartment(data as any);
            setShowDeptModal(false);
          }}
        />
      )}

      {/* Password Rule Modal */}
      {showPwdRuleModal && (
        <PasswordRuleModal
          rule={passwordRule}
          onClose={() => setShowPwdRuleModal(false)}
          onSave={(rule) => { updatePasswordRule(rule); setShowPwdRuleModal(false); }}
        />
      )}
    </div>
  );
}

function MemberModal({ initial, departments, roles, existingUsernames, defaultDeptId, passwordRule, onClose, onSubmit }: {
  initial: Member | null;
  departments: Department[];
  roles: { id: string; name: string }[];
  existingUsernames: string[];
  defaultDeptId: string | null;
  passwordRule: PasswordRule;
  onClose: () => void;
  onSubmit: (data: any) => void;
}) {
  const [name, setName] = useState(initial?.name ?? '');
  const [departmentId, setDepartmentId] = useState(initial?.departmentId ?? defaultDeptId ?? '');
  const [roleId, setRoleId] = useState(initial?.roleId ?? '');
  const [email, setEmail] = useState(initial?.email ?? '');
  const [generatedPassword] = useState(() => generatePassword(passwordRule));
  const password = getDisplayedAccountPassword(initial, generatedPassword);
  const isSystemMember = initial ? isSystemAdminMember(initial) : false;
  const usernamePreview = initial
    ? (initial.username || generateUsernameFromName(initial.name, existingUsernames))
    : (name.trim() ? generateUsernameFromName(name, existingUsernames) : '');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim() || !departmentId || !roleId) return;
    const data: Partial<Member> = { name: name.trim(), departmentId, roleId, email: email.trim(), password };
    if (!initial) {
      data.username = usernamePreview;
      data.phone = '';
    }
    onSubmit(data);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
      <div className="w-full max-w-sm rounded-2xl bg-[var(--bg-card)] border border-[var(--line)] p-5 shadow-[var(--shadow-md)]" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-[13px] font-semibold text-[var(--ink)]">{initial ? '编辑成员' : '新建成员'}</h3>
          <button onClick={onClose} className="p-1 rounded hover:bg-[var(--bg-subtle)] text-[var(--ink-muted)]"><X className="h-4 w-4" /></button>
        </div>
        <form onSubmit={handleSubmit} className="space-y-3">
          {isSystemMember && (
            <div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-[11px] text-amber-700">
              系统内置超级管理员账号不可删除，姓名、部门、角色固定。
            </div>
          )}
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">姓名 *</label>
            <input value={name} onChange={(e) => setName(e.target.value)} required disabled={isSystemMember} placeholder="请输入姓名" className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none disabled:bg-zinc-50 disabled:text-[var(--ink-soft)]" />
          </div>
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">用户名</label>
            <div className="flex h-9 w-full items-center rounded-lg border border-[var(--line)] bg-[var(--bg-subtle)] px-3">
              <span className="flex-1 font-mono text-[13px] text-[var(--ink)]">{usernamePreview || '输入姓名后自动生成'}</span>
              {!initial && (
                <span className="text-[10px] text-[var(--ink-muted)]">自动生成</span>
              )}
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">部门 *</label>
              <select value={departmentId} onChange={(e) => setDepartmentId(e.target.value)} required disabled={isSystemMember} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none disabled:bg-zinc-50 disabled:text-[var(--ink-soft)]">
                <option value="">选择部门</option>
                {departments.map((d) => <option key={d.id} value={d.id}>{d.parentId ? '  ' : ''}{d.name}</option>)}
              </select>
            </div>
            <div>
              <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">角色 *</label>
              <select value={roleId} onChange={(e) => setRoleId(e.target.value)} required disabled={isSystemMember} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none disabled:bg-zinc-50 disabled:text-[var(--ink-soft)]">
                <option value="">选择角色</option>
                {roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">企业邮箱</label>
            <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="name@company.com" className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
          </div>
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">账号密码</label>
            <div className="flex items-center h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-subtle)] px-3">
              <span className="flex-1 text-[13px] font-mono text-[var(--ink)]">{password}</span>
              {!initial && (
                <span className="text-[10px] text-[var(--ink-muted)]">自动生成</span>
              )}
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="h-8 px-3 rounded-lg text-[12px] font-medium border border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]">取消</button>
            <button type="submit" className="h-8 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]">{initial ? '保存' : '创建'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function DeptModal({ initial, departments, onClose, onSubmit }: {
  initial: Department | null;
  departments: Department[];
  onClose: () => void;
  onSubmit: (data: any) => void;
}) {
  const [name, setName] = useState(initial?.name ?? '');
  const [parentId, setParentId] = useState(initial?.parentId ?? '');

  const topDepts = departments.filter((d) => !d.parentId);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    onSubmit({ name: name.trim(), parentId: parentId || undefined, order: departments.length + 1 });
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
      <div className="w-full max-w-xs rounded-2xl bg-[var(--bg-card)] border border-[var(--line)] p-5 shadow-[var(--shadow-md)]" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-[13px] font-semibold text-[var(--ink)]">{initial ? '编辑部门' : '新建部门'}</h3>
          <button onClick={onClose} className="p-1 rounded hover:bg-[var(--bg-subtle)] text-[var(--ink-muted)]"><X className="h-4 w-4" /></button>
        </div>
        <form onSubmit={handleSubmit} className="space-y-3">
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">部门名称 *</label>
            <input value={name} onChange={(e) => setName(e.target.value)} required placeholder="请输入部门名称" className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
          </div>
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">上级部门</label>
            <select value={parentId} onChange={(e) => setParentId(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
              <option value="">无（顶级部门）</option>
              {topDepts.filter((d) => d.id !== initial?.id).map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
            </select>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="h-8 px-3 rounded-lg text-[12px] font-medium border border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]">取消</button>
            <button type="submit" className="h-8 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]">{initial ? '保存' : '创建'}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function PasswordRuleModal({ rule, onClose, onSave }: {
  rule: PasswordRule;
  onClose: () => void;
  onSave: (rule: PasswordRule) => void;
}) {
  const [prefix, setPrefix] = useState(rule.prefix);
  const [length, setLength] = useState(rule.length);
  const [includeUppercase, setIncludeUppercase] = useState(rule.includeUppercase);
  const [includeLowercase, setIncludeLowercase] = useState(rule.includeLowercase);
  const [includeNumbers, setIncludeNumbers] = useState(rule.includeNumbers);
  const [includeSpecial, setIncludeSpecial] = useState(rule.includeSpecial);

  const currentRule: PasswordRule = { prefix, length, includeUppercase, includeLowercase, includeNumbers, includeSpecial };
  const preview = generatePassword(currentRule);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
      <div className="w-full max-w-sm rounded-2xl bg-[var(--bg-card)] border border-[var(--line)] p-5 shadow-[var(--shadow-md)]" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-[13px] font-semibold text-[var(--ink)]">账号密码规则设置</h3>
          <button onClick={onClose} className="p-1 rounded hover:bg-[var(--bg-subtle)] text-[var(--ink-muted)]"><X className="h-4 w-4" /></button>
        </div>
        <div className="space-y-3">
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">固定前缀</label>
              <input value={prefix} onChange={(e) => setPrefix(e.target.value)} placeholder="如 Ftb" className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
            </div>
            <div>
              <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">总长度</label>
              <input type="number" min={6} max={20} value={length} onChange={(e) => setLength(Number(e.target.value))} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
            </div>
          </div>
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-2 block">包含字符类型</label>
            <div className="flex flex-wrap gap-2">
              <label className="flex items-center gap-1.5 text-[12px] text-[var(--ink-soft)] cursor-pointer">
                <input type="checkbox" checked={includeUppercase} onChange={(e) => setIncludeUppercase(e.target.checked)} className="rounded" />
                大写字母
              </label>
              <label className="flex items-center gap-1.5 text-[12px] text-[var(--ink-soft)] cursor-pointer">
                <input type="checkbox" checked={includeLowercase} onChange={(e) => setIncludeLowercase(e.target.checked)} className="rounded" />
                小写字母
              </label>
              <label className="flex items-center gap-1.5 text-[12px] text-[var(--ink-soft)] cursor-pointer">
                <input type="checkbox" checked={includeNumbers} onChange={(e) => setIncludeNumbers(e.target.checked)} className="rounded" />
                数字
              </label>
              <label className="flex items-center gap-1.5 text-[12px] text-[var(--ink-soft)] cursor-pointer">
                <input type="checkbox" checked={includeSpecial} onChange={(e) => setIncludeSpecial(e.target.checked)} className="rounded" />
                特殊字符
              </label>
            </div>
          </div>
          <div>
            <label className="text-[12px] font-medium text-[var(--ink-soft)] mb-1 block">预览效果</label>
            <div className="h-9 flex items-center rounded-lg border border-[var(--line)] bg-[var(--bg-subtle)] px-3">
              <span className="font-mono text-[13px] text-[var(--ink)]">{preview}</span>
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button onClick={onClose} className="h-8 px-3 rounded-lg text-[12px] font-medium border border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]">取消</button>
            <button onClick={() => onSave(currentRule)} className="h-8 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]">保存</button>
          </div>
        </div>
      </div>
    </div>
  );
}
