import { useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import {
  Check,
  KeyRound,
  Layers3,
  Plus,
  Save,
  Search,
  Shield,
  Trash2,
  X,
  UserCog,
  Users,
} from 'lucide-react';
import api from '../services/api';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';
import EmptyState from '../components/EmptyState';

const emptyRoleForm = {
  name: '',
  display_name: '',
  description: '',
  guard_name: 'web',
  permissions: [],
};

const moduleLabels = {
  projects: 'پروژه‌ها',
  tasks: 'تسک‌ها',
  sprints: 'اسپرینت‌ها',
  backlog: 'بک‌لاگ',
  meetings: 'جلسات',
  files: 'فایل‌ها',
  reports: 'گزارش‌ها',
  team: 'تیم',
  roles: 'نقش‌ها',
  settings: 'تنظیمات',
  notifications: 'اعلان‌ها',
  comments: 'نظرات',
  other: 'سایر',
};

const actionLabels = {
  view: 'مشاهده',
  create: 'ایجاد',
  edit: 'ویرایش',
  delete: 'حذف',
  report: 'گزارش',
  export: 'خروجی گرفتن',
  assign: 'تخصیص کاربر',
  upload: 'آپلود',
  approve: 'تأیید',
  reject: 'رد کردن',
  comment: 'ثبت نظر',
  close: 'بستن',
  start: 'شروع',
  end: 'پایان',
  cancel: 'لغو',
};

const actionOrder = ['view', 'create', 'edit', 'assign', 'report', 'export', 'upload', 'comment', 'approve', 'reject', 'start', 'end', 'close', 'cancel', 'delete'];

const flattenPermissionGroups = (groups) => {
  if (!Array.isArray(groups)) return [];
  if (groups.length && groups[0]?.permissions) {
    return groups.flatMap((group) => group.permissions || []);
  }
  return groups;
};

const rolePermissionIds = (role) => (role?.permissions || []).map((permission) => permission.id);
const getModuleLabel = (module) => moduleLabels[module] || module || 'سایر';
const getPermissionLabel = (permission) => {
  const action = permission.name?.split('.')[1];
  return permission.display_name || actionLabels[action] || 'دسترسی';
};
const isDangerPermission = (permission) => permission.name?.endsWith('.delete') || getPermissionLabel(permission).includes('حذف');
const sortPermissions = (items) => [...items].sort((a, b) => {
  const actionA = a.name?.split('.')[1] || '';
  const actionB = b.name?.split('.')[1] || '';
  const indexA = actionOrder.includes(actionA) ? actionOrder.indexOf(actionA) : actionOrder.length;
  const indexB = actionOrder.includes(actionB) ? actionOrder.indexOf(actionB) : actionOrder.length;
  if (indexA !== indexB) return indexA - indexB;
  return getPermissionLabel(a).localeCompare(getPermissionLabel(b), 'fa');
});

export default function Roles() {
  const [roles, setRoles] = useState([]);
  const [permissions, setPermissions] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRoleId, setSelectedRoleId] = useState(null);
  const [permissionDraft, setPermissionDraft] = useState([]);
  const [roleSearch, setRoleSearch] = useState('');
  const [permissionSearch, setPermissionSearch] = useState('');
  const [userSearch, setUserSearch] = useState('');
  const [savingPerms, setSavingPerms] = useState(false);
  const [roleModal, setRoleModal] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [roleForm, setRoleForm] = useState(emptyRoleForm);
  const [savingRole, setSavingRole] = useState(false);
  const [roleWizardStep, setRoleWizardStep] = useState(0);
  const [roleModuleIndex, setRoleModuleIndex] = useState(0);
  const [deletingRole, setDeletingRole] = useState(null);
  const [userRoleDrafts, setUserRoleDrafts] = useState({});
  const [savingUserId, setSavingUserId] = useState(null);

  const fetchAll = async () => {
    setLoading(true);
    try {
      const [rolesRes, permissionsRes, usersRes] = await Promise.all([
        api.get('/roles', { params: { per_page: 300, sort_by: 'name', sort_dir: 'asc' } }),
        api.get('/permissions'),
        api.get('/users', { params: { per_page: 300, sort_by: 'name', sort_dir: 'asc' } }),
      ]);
      const nextRoles = rolesRes.data.data || [];
      const nextPermissions = flattenPermissionGroups(permissionsRes.data.data || []);
      const nextUsers = usersRes.data.data || [];
      setRoles(nextRoles);
      setPermissions(nextPermissions);
      setUsers(nextUsers);
      setUserRoleDrafts(Object.fromEntries(nextUsers.map((user) => [user.id, (user.roles || []).map((role) => role.id)])));
      setSelectedRoleId((current) => current || nextRoles[0]?.id || null);
    } catch {
      toast.error('خطا در دریافت نقش‌ها و دسترسی‌ها');
    } finally {
      setLoading(false);
    }
  };

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

  const selectedRole = useMemo(() => roles.find((role) => role.id === selectedRoleId) || roles[0] || null, [roles, selectedRoleId]);

  useEffect(() => {
    if (selectedRole) setPermissionDraft(rolePermissionIds(selectedRole));
  }, [selectedRole]);

  const filteredRoles = useMemo(() => {
    const q = roleSearch.trim().toLowerCase();
    return roles.filter((role) => !q || role.name.toLowerCase().includes(q) || role.display_name?.toLowerCase().includes(q));
  }, [roles, roleSearch]);

  const permissionGroups = useMemo(() => {
    const q = permissionSearch.trim().toLowerCase();
    return permissions
      .filter((permission) => !q || permission.name.toLowerCase().includes(q) || permission.display_name?.toLowerCase().includes(q) || permission.module?.toLowerCase().includes(q))
      .reduce((acc, permission) => {
        const module = permission.module || permission.name?.split('.')[0] || 'other';
        if (!acc[module]) acc[module] = [];
        acc[module].push(permission);
        return acc;
      }, {});
  }, [permissions, permissionSearch]);

  const rolePermissionModules = useMemo(() => {
    const groups = permissions.reduce((acc, permission) => {
      const module = permission.module || permission.name?.split('.')[0] || 'other';
      if (!acc[module]) acc[module] = [];
      acc[module].push(permission);
      return acc;
    }, {});
    return Object.entries(groups).sort(([moduleA], [moduleB]) => getModuleLabel(moduleA).localeCompare(getModuleLabel(moduleB), 'fa'));
  }, [permissions]);

  const filteredUsers = useMemo(() => {
    const q = userSearch.trim().toLowerCase();
    return users.filter((user) => !q || user.name?.toLowerCase().includes(q) || user.email?.toLowerCase().includes(q));
  }, [users, userSearch]);

  const summary = useMemo(() => ({
    roles: roles.length,
    permissions: permissions.length,
    users: users.length,
    modules: new Set(permissions.map((permission) => permission.module)).size,
  }), [roles, permissions, users]);

  const permissionsChanged = selectedRole && JSON.stringify([...permissionDraft].sort()) !== JSON.stringify(rolePermissionIds(selectedRole).sort());

  const togglePermission = (permissionId) => {
    setPermissionDraft((prev) => prev.includes(permissionId) ? prev.filter((id) => id !== permissionId) : [...prev, permissionId]);
  };

  const setModulePermissions = (modulePermissions, checked) => {
    const ids = modulePermissions.map((permission) => permission.id);
    setPermissionDraft((prev) => checked ? Array.from(new Set([...prev, ...ids])) : prev.filter((id) => !ids.includes(id)));
  };

  const saveRolePermissions = async () => {
    if (!selectedRole) return;
    setSavingPerms(true);
    try {
      const { data } = await api.post(`/roles/${selectedRole.id}/permissions`, { permissions: permissionDraft });
      const updated = data.data;
      setRoles((prev) => prev.map((role) => role.id === updated.id ? updated : role));
      setPermissionDraft(rolePermissionIds(updated));
      toast.success('دسترسی‌های نقش ذخیره شد');
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در ذخیره دسترسی‌ها');
    } finally {
      setSavingPerms(false);
    }
  };

  const openCreateRole = () => {
    setEditingRole(null);
    setRoleForm(emptyRoleForm);
    setRoleWizardStep(0);
    setRoleModuleIndex(0);
    setRoleModal(true);
  };

  const openEditRole = (role) => {
    setEditingRole(role);
    setRoleForm({
      name: role.name || '',
      display_name: role.display_name || '',
      description: role.description || '',
      guard_name: role.guard_name || 'web',
      permissions: rolePermissionIds(role),
    });
    setRoleWizardStep(0);
    setRoleModuleIndex(0);
    setRoleModal(true);
  };

  const saveRole = async (e) => {
    e.preventDefault();
    if (!roleForm.name.trim() || !roleForm.display_name.trim()) {
      toast.error('نام سیستمی و نام نمایشی الزامی است');
      return;
    }
    setSavingRole(true);
    try {
      const payload = {
        ...roleForm,
        name: roleForm.name.trim(),
        display_name: roleForm.display_name.trim(),
      };
      const { data } = editingRole
        ? await api.put(`/roles/${editingRole.id}`, payload)
        : await api.post('/roles', payload);
      const saved = data.data;
      setRoles((prev) => editingRole ? prev.map((role) => role.id === saved.id ? saved : role) : [...prev, saved]);
      setSelectedRoleId(saved.id);
      setRoleModal(false);
      toast.success(editingRole ? 'نقش به‌روزرسانی شد' : 'نقش جدید ایجاد شد');
    } catch (err) {
      const firstError = Object.values(err.response?.data?.errors || {})[0]?.[0];
      toast.error(firstError || err.response?.data?.message || 'خطا در ذخیره نقش');
    } finally {
      setSavingRole(false);
    }
  };

  const deleteRole = async () => {
    try {
      await api.delete(`/roles/${deletingRole.id}`);
      setRoles((prev) => prev.filter((role) => role.id !== deletingRole.id));
      setUsers((prev) => prev.map((user) => ({ ...user, roles: (user.roles || []).filter((role) => role.id !== deletingRole.id) })));
      setUserRoleDrafts((prev) => Object.fromEntries(Object.entries(prev).map(([userId, roleIds]) => [userId, roleIds.filter((roleId) => roleId !== deletingRole.id)])));
      setSelectedRoleId((current) => current === deletingRole.id ? roles.find((role) => role.id !== deletingRole.id)?.id || null : current);
      setDeletingRole(null);
      toast.success('نقش حذف شد');
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در حذف نقش');
    }
  };

  const toggleRoleFormPermission = (permissionId) => {
    setRoleForm((prev) => ({
      ...prev,
      permissions: prev.permissions.includes(permissionId)
        ? prev.permissions.filter((id) => id !== permissionId)
        : [...prev.permissions, permissionId],
    }));
  };

  const toggleUserRole = (userId, roleId) => {
    setUserRoleDrafts((prev) => {
      const current = prev[userId] || [];
      return {
        ...prev,
        [userId]: current.includes(roleId) ? current.filter((id) => id !== roleId) : [...current, roleId],
      };
    });
  };

  const saveUserRoles = async (user) => {
    setSavingUserId(user.id);
    try {
      const { data } = await api.put(`/users/${user.id}/roles`, { roles: userRoleDrafts[user.id] || [] });
      const updated = data.data;
      setUsers((prev) => prev.map((item) => item.id === updated.id ? updated : item));
      setUserRoleDrafts((prev) => ({ ...prev, [updated.id]: (updated.roles || []).map((role) => role.id) }));
      toast.success('سطح دسترسی کاربر ذخیره شد');
    } catch (err) {
      toast.error(err.response?.data?.message || 'خطا در ذخیره نقش‌های کاربر');
    } finally {
      setSavingUserId(null);
    }
  };

  if (loading) {
    return (
      <div className="page-container access-page">
        <div className="skeleton" style={{ height: 620, borderRadius: 'var(--radius)' }} />
      </div>
    );
  }

  return (
    <div className="page-container access-page">
      <div className="page-header access-header">
        <div>
        </div>
        <button className="btn btn-primary" onClick={openCreateRole}><Plus size={16} /> نقش جدید</button>
      </div>

      <div className="access-summary">
        <SummaryItem label="نقش‌ها" value={summary.roles} icon={Shield} />
        <SummaryItem label="دسترسی‌ها" value={summary.permissions} icon={KeyRound} />
        <SummaryItem label="ماژول‌ها" value={summary.modules} icon={Layers3} />
        <SummaryItem label="کاربران" value={summary.users} icon={Users} />
      </div>

      {roles.length === 0 ? (
        <EmptyState icon={Shield} title="نقشی وجود ندارد" description="برای شروع یک نقش جدید تعریف کنید." action={<button className="btn btn-primary" onClick={openCreateRole}>ایجاد نقش</button>} />
      ) : (
        <div className="access-layout">
          <aside className="access-roles-panel">
            <div className="access-panel-head">
              <strong>سطوح دسترسی</strong>
              <span>{filteredRoles.length} نقش</span>
            </div>
            <div className="access-search">
              <Search size={15} />
              <input className="form-input" value={roleSearch} onChange={(e) => setRoleSearch(e.target.value)} placeholder="جستجوی نقش" />
            </div>
            <div className="access-role-list">
              {filteredRoles.map((role) => (
                <button key={role.id} className={`access-role-item ${selectedRole?.id === role.id ? 'active' : ''}`} onClick={() => setSelectedRoleId(role.id)}>
                  <span>
                    <strong>{role.display_name || role.name}</strong>
                    <small>{(role.permissions || []).length} دسترسی فعال</small>
                  </span>
                  <em>{(role.permissions || []).length}</em>
                </button>
              ))}
            </div>
          </aside>

          <main className="access-main">
            <section className="access-card access-role-detail">
              <div className="access-detail-head">
                <div>
                  <span className="badge badge-info">{selectedRole?.guard_name === 'web' ? 'وب' : 'سامانه'}</span>
                  <h2>{selectedRole?.display_name || selectedRole?.name}</h2>
                  <p>{selectedRole?.description || 'توضیحی برای این نقش ثبت نشده است.'}</p>
                </div>
                <div className="access-detail-actions">
                  <button className="btn btn-secondary btn-sm" onClick={() => openEditRole(selectedRole)}>ویرایش نقش</button>
                  <button className="btn btn-danger btn-sm" onClick={() => setDeletingRole(selectedRole)}><Trash2 size={14} /> حذف</button>
                </div>
              </div>
              <div className="access-role-stats">
                <Info label="کاربران این نقش" value={selectedRole?.users_count ?? users.filter((user) => (user.roles || []).some((role) => role.id === selectedRole?.id)).length} />
                <Info label="دسترسی‌های فعال" value={permissionDraft.length} />
                <Info label="کل دسترسی‌ها" value={permissions.length} />
              </div>
            </section>

            <section className="access-card">
              <div className="access-section-head">
                <div>
                  <h3>دسترسی‌های نقش</h3>
                  <span>هر تغییر با ذخیره روی همین نقش اعمال می‌شود.</span>
                </div>
                <div className="access-search compact">
                  <Search size={15} />
                  <input className="form-input" value={permissionSearch} onChange={(e) => setPermissionSearch(e.target.value)} placeholder="جستجوی دسترسی" />
                </div>
              </div>

              <PermissionMatrix
                groups={permissionGroups}
                selectedIds={permissionDraft}
                onToggle={togglePermission}
                onToggleModule={setModulePermissions}
              />

              <div className="access-save-bar">
                <button className="btn btn-secondary btn-sm" disabled={!permissionsChanged} onClick={() => setPermissionDraft(rolePermissionIds(selectedRole))}>بازنشانی</button>
                <button className="btn btn-primary btn-sm" disabled={!permissionsChanged || savingPerms} onClick={saveRolePermissions}>
                  <Save size={15} />
                  {savingPerms ? 'در حال ذخیره...' : 'ذخیره دسترسی‌ها'}
                </button>
              </div>
            </section>

            <section className="access-card">
              <div className="access-section-head">
                <div>
                  <h3>سطح دسترسی کاربران</h3>
                  <span>برای هر کاربر می‌توانید یک یا چند نقش انتخاب کنید.</span>
                </div>
                <div className="access-search compact">
                  <Search size={15} />
                  <input className="form-input" value={userSearch} onChange={(e) => setUserSearch(e.target.value)} placeholder="جستجوی کاربر" />
                </div>
              </div>

              <div className="access-user-list">
                {filteredUsers.map((user) => {
                  const originalRoleIds = (user.roles || []).map((role) => role.id);
                  const draftRoleIds = userRoleDrafts[user.id] || [];
                  const changed = JSON.stringify([...originalRoleIds].sort()) !== JSON.stringify([...draftRoleIds].sort());
                  return (
                    <div className="access-user-row" key={user.id}>
                      <div className="avatar avatar-sm">{user.name?.[0] || '?'}</div>
                      <div className="access-user-title">
                        <strong>{user.name}</strong>
                        <span>{user.email}</span>
                      </div>
                      <div className="access-user-roles">
                        {roles.map((role) => (
                          <button
                            key={role.id}
                            type="button"
                            className={`access-chip ${draftRoleIds.includes(role.id) ? 'checked' : ''}`}
                            aria-pressed={draftRoleIds.includes(role.id)}
                            onClick={() => toggleUserRole(user.id, role.id)}
                          >
                            {role.display_name || role.name}
                          </button>
                        ))}
                      </div>
                      <button className="btn btn-primary btn-sm" disabled={!changed || savingUserId === user.id} onClick={() => saveUserRoles(user)}>
                        <UserCog size={14} />
                        {savingUserId === user.id ? '...' : 'ذخیره'}
                      </button>
                    </div>
                  );
                })}
              </div>
            </section>
          </main>
        </div>
      )}

      {roleModal && (
        <Modal title={editingRole ? 'ویرایش نقش' : 'نقش جدید'} size="xl" onClose={() => setRoleModal(false)} footer={
          roleWizardStep === 0 ? (
            <>
              <button className="btn btn-secondary" onClick={() => setRoleModal(false)}>انصراف</button>
              <button className="btn btn-primary" onClick={() => setRoleWizardStep(1)}>مرحله بعد: دسترسی‌ها</button>
            </>
          ) : (
            <>
              <button className="btn btn-secondary" onClick={() => setRoleWizardStep(0)}>مرحله قبل</button>
              <button className="btn btn-primary" onClick={saveRole} disabled={savingRole}>
                <Save size={16} />
                {savingRole ? 'در حال ذخیره...' : 'ذخیره نقش'}
              </button>
            </>
          )
        }>
          <form className="access-role-form" onSubmit={saveRole}>
            <div className="modal-wizard-steps modal-wizard-steps-two" role="tablist" aria-label="مراحل تعریف نقش">
              <button type="button" role="tab" aria-selected={roleWizardStep === 0} className={roleWizardStep === 0 ? 'active' : 'complete'} onClick={() => setRoleWizardStep(0)}><span>{roleWizardStep > 0 ? <Check size={16} /> : '۱'}</span>مشخصات نقش</button>
              <button type="button" role="tab" aria-selected={roleWizardStep === 1} className={roleWizardStep === 1 ? 'active' : ''} onClick={() => setRoleWizardStep(1)}><span>۲</span>دسترسی‌ها</button>
            </div>
            {roleWizardStep === 0 ? (
              <div className="role-wizard-details">
                <div className="grid grid-2">
                  <Field label="نام سیستمی">
                    <input className="form-input" value={roleForm.name} onChange={(e) => setRoleForm({ ...roleForm, name: e.target.value })} disabled={!!editingRole} placeholder="نام نقش" />
                  </Field>
                  <Field label="نام نمایشی">
                    <input className="form-input" value={roleForm.display_name} onChange={(e) => setRoleForm({ ...roleForm, display_name: e.target.value })} placeholder="نقش سفارشی" />
                  </Field>
                </div>
                <Field label="توضیحات">
                  <textarea className="form-textarea" value={roleForm.description} onChange={(e) => setRoleForm({ ...roleForm, description: e.target.value })} />
                </Field>
              </div>
            ) : (
              <div className="access-form-permissions role-permission-wizard">
                <div className="access-section-head tight">
                  <div>
                    <h3>{rolePermissionModules[roleModuleIndex] ? getModuleLabel(rolePermissionModules[roleModuleIndex][0]) : 'دسترسی‌های نقش'}</h3>
                    <span>{roleForm.permissions.length} دسترسی انتخاب شده</span>
                  </div>
                </div>
                <PermissionMatrix
                  groups={rolePermissionModules[roleModuleIndex] ? Object.fromEntries([rolePermissionModules[roleModuleIndex]]) : {}}
                  selectedIds={roleForm.permissions}
                  onToggle={toggleRoleFormPermission}
                  onToggleModule={(modulePermissions, checked) => {
                    const ids = modulePermissions.map((permission) => permission.id);
                    setRoleForm((prev) => ({
                      ...prev,
                      permissions: checked ? Array.from(new Set([...prev.permissions, ...ids])) : prev.permissions.filter((id) => !ids.includes(id)),
                    }));
                  }}
                />
                <div className="schedule-wizard-navigation">
                  <button type="button" className="btn btn-secondary btn-sm" disabled={roleModuleIndex === 0} onClick={() => setRoleModuleIndex((index) => Math.max(0, index - 1))}>ماژول قبلی</button>
                  <span>{rolePermissionModules.length ? roleModuleIndex + 1 : 0} از {rolePermissionModules.length}</span>
                  <button type="button" className="btn btn-secondary btn-sm" disabled={roleModuleIndex >= rolePermissionModules.length - 1} onClick={() => setRoleModuleIndex((index) => Math.min(rolePermissionModules.length - 1, index + 1))}>ماژول بعدی</button>
                </div>
              </div>
            )}
          </form>
        </Modal>
      )}

      {deletingRole && (
        <ConfirmDialog
          danger
          title="حذف نقش"
          message={`آیا از حذف نقش "${deletingRole.display_name || deletingRole.name}" مطمئن هستید؟ این نقش از کاربران هم برداشته می‌شود.`}
          confirmText="حذف نقش"
          onConfirm={deleteRole}
          onCancel={() => setDeletingRole(null)}
        />
      )}
    </div>
  );
}

function PermissionMatrix({ groups, selectedIds, onToggle, onToggleModule }) {
  const entries = Object.entries(groups).sort(([moduleA], [moduleB]) => getModuleLabel(moduleA).localeCompare(getModuleLabel(moduleB), 'fa'));
  if (!entries.length) {
    return <div className="access-empty"><KeyRound size={28} /><span>دسترسی‌ای یافت نشد</span></div>;
  }

  return (
    <div className="access-permission-groups">
      {entries.map(([module, modulePermissions]) => {
        const sortedPermissions = sortPermissions(modulePermissions);
        const selectedCount = sortedPermissions.filter((permission) => selectedIds.includes(permission.id)).length;
        const allChecked = selectedCount === sortedPermissions.length;
        return (
          <div className="access-permission-module" key={module}>
            <div className="access-module-head">
              <div>
                <strong>{getModuleLabel(module)}</strong>
                <span>{selectedCount} از {sortedPermissions.length} دسترسی فعال</span>
              </div>
              <button type="button" className={`access-module-toggle ${allChecked ? 'checked' : ''}`} onClick={() => onToggleModule(sortedPermissions, !allChecked)} aria-pressed={allChecked}>
                <span>{allChecked ? 'همه فعال' : 'فعال‌سازی همه'}</span>
                <strong>{allChecked ? <Check size={14} /> : <X size={14} />}</strong>
              </button>
            </div>
            <div className="access-permission-grid">
              {sortedPermissions.map((permission) => {
                const checked = selectedIds.includes(permission.id);
                const danger = isDangerPermission(permission);
                return (
                  <button
                    key={permission.id}
                    type="button"
                    className={`access-permission ${checked ? 'checked' : ''} ${danger ? 'danger' : ''}`}
                    aria-pressed={checked}
                    onClick={() => onToggle(permission.id)}
                  >
                    <span className="access-toggle-indicator">{checked ? <Check size={14} /> : <X size={14} />}</span>
                    <span>{getPermissionLabel(permission)}</span>
                  </button>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function SummaryItem({ label, value, icon: Icon }) {
  return (
    <div className="access-stat">
      <Icon size={18} />
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}

function Info({ label, value }) {
  return <div className="access-info"><span>{label}</span><strong>{value ?? '—'}</strong></div>;
}

function Field({ label, children }) {
  return <div className="form-group"><label className="form-label">{label}</label>{children}</div>;
}
