'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { App, Button, Checkbox, Form, Input, Popconfirm, Select, Tag, Tooltip } from 'antd';
import { Icon, type IconName } from '../ui/Icon';
import { DataTable, PageHeader, type DataTableColumn } from '../platform/PlatformPrimitives';
import { CRM_MODULES, MODULE_META, SIDEBAR_MODULES, rolesApi, type CrmModule, type RolePermissionItem, type RoleRecord } from '../../lib/roles';

function initializeMatrix(existing?: RolePermissionItem[]): Record<CrmModule, RolePermissionItem> {
  const existingMap = new Map<string, RolePermissionItem>();
  (existing || []).forEach((p) => existingMap.set(p.module, p));

  const result = {} as Record<CrmModule, RolePermissionItem>;
  CRM_MODULES.forEach((mod) => {
    const found = existingMap.get(mod);
    result[mod] = {
      module: mod,
      canRead: found ? Boolean(found.canRead) : false,
      canCreate: found ? Boolean(found.canCreate) : false,
      canUpdate: found ? Boolean(found.canUpdate) : false,
      canDelete: found ? Boolean(found.canDelete) : false,
      canExport: found ? Boolean(found.canExport) : false,
    };
  });
  return result;
}

export function RolesEditorView({ isAdmin }: { isAdmin: boolean; onNavigateToUsers?: () => void }) {
  const { message } = App.useApp();

  const [roles, setRoles] = useState<RoleRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  // View state: 'list' | 'editor'
  const [viewMode, setViewMode] = useState<'list' | 'editor'>('list');
  const [editingRole, setEditingRole] = useState<RoleRecord | null>(null);

  // Search & Filter state
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState<'ALL' | 'CUSTOM' | 'SYSTEM'>('ALL');
  const [page, setPage] = useState(1);
  const pageSize = 10;

  // Editor form state
  const [form] = Form.useForm();
  const [saving, setSaving] = useState(false);
  const [matrix, setMatrix] = useState<Record<CrmModule, RolePermissionItem>>(() => initializeMatrix());

  const loadRoles = useCallback(async () => {
    setLoading(true);
    try {
      const data = await rolesApi.list();
      setRoles(data);
    } catch (err: unknown) {
      message.error(err instanceof Error ? err.message : 'Failed to load roles');
    } finally {
      setLoading(false);
    }
  }, [message]);

  useEffect(() => {
    let ignore = false;
    rolesApi
      .list()
      .then((data) => {
        if (!ignore) {
          setRoles(data);
          setLoading(false);
        }
      })
      .catch((err: unknown) => {
        if (!ignore) {
          message.error(err instanceof Error ? err.message : 'Failed to load roles');
          setLoading(false);
        }
      });
    return () => {
      ignore = true;
    };
  }, [message]);

  const handleOpenCreate = () => {
    setEditingRole(null);
    // When creating a new role manually, start with standard read permissions
    const initial = initializeMatrix();
    CRM_MODULES.forEach((m) => {
      initial[m].canRead = true;
    });
    setMatrix(initial);
    setViewMode('editor');
  };

  const handleOpenEdit = useCallback((role: RoleRecord) => {
    setEditingRole(role);
    setMatrix(initializeMatrix(role.permissions));
    setViewMode('editor');
  }, []);

  const handleBackToList = () => {
    setViewMode('list');
    setEditingRole(null);
  };

  const handleDelete = useCallback(
    async (role: RoleRecord) => {
      if (role.isSystem) {
        message.error('System roles cannot be deleted');
        return;
      }

      setDeletingId(role.id);
      try {
        await rolesApi.delete(role.id);
        message.success(`Role "${role.name}" deleted successfully`);
        void loadRoles();
      } catch (err: unknown) {
        message.error(err instanceof Error ? err.message : 'Failed to delete role');
      } finally {
        setDeletingId(null);
      }
    },
    [loadRoles, message],
  );

  // Matrix manipulation helpers
  const handleCellToggle = (module: CrmModule, action: 'canCreate' | 'canRead' | 'canUpdate' | 'canDelete' | 'canExport') => {
    setMatrix((prev) => {
      const current = prev[module];
      const nextVal = !current[action];
      const updated = { ...current, [action]: nextVal };

      // Enabling create, update, delete or export automatically enables view
      if (nextVal && action !== 'canRead') {
        updated.canRead = true;
      }
      // Disabling view automatically disables create, update, delete, export
      if (!nextVal && action === 'canRead') {
        updated.canCreate = false;
        updated.canUpdate = false;
        updated.canDelete = false;
        updated.canExport = false;
      }

      return { ...prev, [module]: updated };
    });
  };

  const handleRowToggleAll = (module: CrmModule) => {
    setMatrix((prev) => {
      const current = prev[module];
      const allActive = current.canCreate && current.canRead && current.canUpdate && current.canDelete && current.canExport;
      const nextVal = !allActive;

      return {
        ...prev,
        [module]: {
          module,
          canRead: nextVal,
          canCreate: nextVal,
          canUpdate: nextVal,
          canDelete: nextVal,
          canExport: nextVal,
        },
      };
    });
  };

  const handleColumnToggleAll = (action: 'canCreate' | 'canRead' | 'canUpdate' | 'canDelete' | 'canExport') => {
    setMatrix((prev) => {
      const allChecked = CRM_MODULES.every((m) => prev[m][action]);
      const nextVal = !allChecked;

      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        const item = { ...updated[m], [action]: nextVal };
        if (nextVal && action !== 'canRead') {
          item.canRead = true;
        }
        if (!nextVal && action === 'canRead') {
          item.canCreate = false;
          item.canUpdate = false;
          item.canDelete = false;
          item.canExport = false;
        }
        updated[m] = item;
      });
      return updated;
    });
  };

  // Presets
  const handleFullAccessPreset = () => {
    setMatrix((prev) => {
      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        updated[m] = {
          module: m,
          canRead: true,
          canCreate: true,
          canUpdate: true,
          canDelete: true,
          canExport: true,
        };
      });
      return updated;
    });
  };

  const handleReadOnlyPreset = () => {
    setMatrix((prev) => {
      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        updated[m] = {
          module: m,
          canRead: m !== 'users_roles' && m !== 'roles',
          canCreate: false,
          canUpdate: false,
          canDelete: false,
          canExport: false,
        };
      });
      return updated;
    });
  };

  const handleClearAll = () => {
    setMatrix((prev) => {
      const updated = { ...prev };
      CRM_MODULES.forEach((m) => {
        updated[m] = {
          module: m,
          canRead: false,
          canCreate: false,
          canUpdate: false,
          canDelete: false,
          canExport: false,
        };
      });
      return updated;
    });
  };

  const handleSaveRole = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);

      const permissionsArray = CRM_MODULES.map((m) => {
        if (m === 'contacts') return { ...matrix['accounts'], module: 'contacts' as CrmModule };
        if (m === 'timesheets') return { ...matrix['projects'], module: 'timesheets' as CrmModule };
        if (m === 'tasks' || m === 'activities') return { ...matrix['leads'], module: m as CrmModule };
        return matrix[m] || { module: m, canRead: false, canCreate: false, canUpdate: false, canDelete: false, canExport: false };
      });

      if (editingRole) {
        await rolesApi.update(editingRole.id, {
          name: values.name.trim(),
          description: values.description ? values.description.trim() : undefined,
          permissions: permissionsArray,
        });
        message.success(`Role "${values.name}" updated successfully`);
      } else {
        await rolesApi.create({
          name: values.name.trim(),
          description: values.description ? values.description.trim() : undefined,
          permissions: permissionsArray,
        });
        message.success(`Role "${values.name}" created successfully`);
      }

      setViewMode('list');
      setEditingRole(null);
      void loadRoles();
    } catch (err: unknown) {
      message.error(err instanceof Error ? err.message : 'Failed to save role');
    } finally {
      setSaving(false);
    }
  };

  // Stats calculation
  const totalRoles = roles.length;
  const customRolesCount = roles.filter((r) => !r.isSystem).length;
  const systemRolesCount = roles.filter((r) => r.isSystem).length;
  const totalAssignedUsers = roles.reduce((sum, r) => sum + (r.userCount || 0), 0);

  // Filter computation
  const filteredRoles = useMemo(() => {
    const q = search.trim().toLowerCase();
    return roles.filter((r) => {
      if (typeFilter === 'CUSTOM' && r.isSystem) return false;
      if (typeFilter === 'SYSTEM' && !r.isSystem) return false;
      if (q) {
        const match = r.name.toLowerCase().includes(q) || (r.description && r.description.toLowerCase().includes(q));
        if (!match) return false;
      }
      return true;
    });
  }, [roles, typeFilter, search]);

  const safePage = Math.min(page, Math.max(1, Math.ceil(filteredRoles.length / pageSize)));
  const pageRows = filteredRoles.slice((safePage - 1) * pageSize, safePage * pageSize);

  const columns = useMemo<DataTableColumn<RoleRecord>[]>(
    () => [
      {
        key: 'name',
        label: 'Role',
        render: (_, r: RoleRecord) => (
          <div className="py-0.5">
            <div className="font-semibold text-[13.5px] text-[var(--tcx-text)]">{r.name}</div>
            <div className="mt-0.5 text-[12px] text-[var(--tcx-muted)]">{r.description || 'No description provided.'}</div>
          </div>
        ),
      },
      {
        key: 'type',
        label: 'Type',
        width: 120,
        render: (_, r: RoleRecord) => (
          <Tag color={r.isSystem ? 'blue' : 'cyan'} className="font-medium text-[11px]">
            {r.isSystem ? 'System' : 'Custom'}
          </Tag>
        ),
      },
      {
        key: 'permissions',
        label: 'Permissions Access',
        render: (_, r: RoleRecord) => {
          const activeModules = (r.permissions || []).filter((p) => SIDEBAR_MODULES.includes(p.module as CrmModule) && (p.canCreate || p.canRead || p.canUpdate || p.canDelete || p.canExport));
          const isFullAccess = activeModules.length === SIDEBAR_MODULES.length && activeModules.every((p) => p.canCreate && p.canRead && p.canUpdate && p.canDelete && p.canExport);

          if (isFullAccess) {
            return (
              <Tag color="green" className="font-medium text-[11.5px]">
                ● Full Access (All {SIDEBAR_MODULES.length} Modules)
              </Tag>
            );
          }
          if (activeModules.length === 0) {
            return <Tag className="text-[11.5px] text-[var(--tcx-muted)]">No permissions configured</Tag>;
          }
          return (
            <Tooltip
              title={
                <div>
                  <div className="font-semibold mb-1">Permitted Modules:</div>
                  {activeModules.map((p) => {
                    const meta = MODULE_META[p.module as CrmModule];
                    const acts = [p.canRead ? 'View' : null, p.canCreate ? 'Create' : null, p.canUpdate ? 'Edit' : null, p.canDelete ? 'Delete' : null, p.canExport ? 'Export' : null].filter(Boolean).join(', ');
                    return (
                      <div key={p.module} className="text-[11px]">
                        • {meta?.label || p.module}: {acts}
                      </div>
                    );
                  })}
                </div>
              }
            >
              <Tag color="geekblue" className="cursor-pointer font-medium text-[11.5px]">
                {activeModules.length} of {SIDEBAR_MODULES.length} modules enabled ⓘ
              </Tag>
            </Tooltip>
          );
        },
      },
      {
        key: 'users',
        label: 'Assigned Users',
        width: 160,
        render: (_, r: RoleRecord) => (
          <span className="flex items-center gap-1.5 text-[12.5px] text-[var(--tcx-muted)]">
            <Icon name="contacts" size={14} />
            <strong className="text-[var(--tcx-text)]">{r.userCount}</strong> {r.userCount === 1 ? 'user' : 'users'}
          </span>
        ),
      },
      {
        key: 'actions',
        label: 'Actions',
        right: true,
        width: 160,
        render: (_, r: RoleRecord) => (
          <div className="inline-flex items-center justify-end gap-1.5" onClick={(e) => e.stopPropagation()}>
            {isAdmin && (
              <>
                <Button size="small" type="text" icon={<Icon name={r.isSystem ? 'eye' : 'edit'} size={14} />} onClick={() => handleOpenEdit(r)}>
                  {r.isSystem ? 'View permissions' : 'Edit'}
                </Button>

                {!r.isSystem && (
                  <Popconfirm title={`Delete "${r.name}" role?`} description={r.userCount > 0 ? `This role is assigned to ${r.userCount} user(s). Deleting it will unassign them from this role. Continue?` : 'Are you sure you want to permanently delete this role?'} okText="Delete" cancelText="Cancel" okButtonProps={{ danger: true }} onConfirm={() => handleDelete(r)}>
                    <Button size="small" type="text" danger aria-label={`Delete role ${r.name}`} loading={deletingId === r.id} icon={<Icon name="trash" size={14} />} />
                  </Popconfirm>
                )}
              </>
            )}
          </div>
        ),
      },
    ],
    [isAdmin, deletingId, handleOpenEdit, handleDelete],
  );

  if (viewMode === 'editor') {
    return (
      <div>
        {/* Top Header */}
        <div className="mb-6 flex flex-wrap items-center justify-between gap-4 border-b border-[var(--tcx-border)] pb-4">
          <div className="flex items-center gap-3">
            <Button icon={<Icon name="chevronLeft" size={15} />} onClick={handleBackToList}>
              Back to roles
            </Button>
            <div>
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--tcx-muted)]">USERS & ACCESS / ROLES</div>
              <h2 className="m-0 text-[20px] font-bold text-[var(--tcx-text)]">{editingRole ? `Edit Role: ${editingRole.name}` : 'Create New Custom Role'}</h2>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <Button onClick={handleBackToList} disabled={saving}>
              {editingRole?.isSystem ? 'Back to Roles' : 'Cancel'}
            </Button>
            {!editingRole?.isSystem && (
              <Button type="primary" loading={saving} onClick={handleSaveRole} icon={<Icon name="shield" size={15} />}>
                {editingRole ? 'Save Changes' : 'Create Role'}
              </Button>
            )}
          </div>
        </div>

        {/* Role Details Card */}
        <div className="tcx-surface-card p-6 mb-6">
          <h3 className="mb-1 text-[15px] font-semibold text-[var(--tcx-text)]">Role Information</h3>
          <p className="mb-4 text-[13px] text-[var(--tcx-muted)]">Define a unique title and clear description for this role.</p>

          <Form preserve={false} form={form} layout="vertical" initialValues={{ name: editingRole?.name ?? '', description: editingRole?.description ?? '' }}>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <Form.Item
                name="name"
                label={<span className="font-semibold text-[13px]">Role Name</span>}
                rules={[
                  { required: true, message: 'Role name is required' },
                  { max: 100, message: 'Maximum 100 characters' },
                ]}
              >
                <Input placeholder="Enter custom role title" disabled={editingRole?.isSystem} className="rounded-lg py-2" />
              </Form.Item>

              <Form.Item name="description" label={<span className="font-semibold text-[13px]">Description</span>} rules={[{ max: 255, message: 'Maximum 255 characters' }]}>
                <Input placeholder="Summary of responsibilities and authorization boundaries" className="rounded-lg py-2" />
              </Form.Item>
            </div>

            {editingRole?.isSystem && (
              <div className="rounded-lg bg-blue-50/70 p-3.5 text-[12.5px] text-blue-800 dark:bg-blue-950/40 dark:text-blue-300 border border-blue-200 dark:border-blue-900/50">
                <span className="font-semibold">System Administrator:</span> This is the built-in system role. Organization Administrators have full, unrestricted access to all modules, settings, and destructive actions. Permissions cannot be restricted.
              </div>
            )}
          </Form>
        </div>

        {/* Permissions Table Card */}
        <div className="tcx-surface-card p-6">
          <div className="flex flex-wrap items-start justify-between gap-3 border-b border-[var(--tcx-border)] pb-4">
            <div>
              <h3 className="mb-1 text-[16px] font-bold text-[var(--tcx-text)]">Module Permissions</h3>
              <p className="m-0 text-[13px] text-[var(--tcx-muted)]">Check the actions permitted for each module. Granting Create, Edit, Delete, or Export automatically grants View access.</p>
            </div>

            {/* Presets */}
            {!editingRole?.isSystem && (
              <div className="flex flex-wrap items-center gap-1.5">
                <span className="mr-1 text-[12px] font-medium text-[var(--tcx-muted)]">Presets:</span>
                <Button size="small" onClick={handleFullAccessPreset}>
                  Full Access
                </Button>
                <Button size="small" onClick={handleReadOnlyPreset}>
                  Read Only
                </Button>
                <Button size="small" danger onClick={handleClearAll}>
                  Clear All
                </Button>
              </div>
            )}
          </div>

          {/* Column quick actions */}
          {!editingRole?.isSystem && (
            <div className="flex flex-wrap items-center justify-between border-b border-[var(--tcx-border)] bg-[var(--tcx-surface-2)] px-4 py-2.5 text-[12px] text-[var(--tcx-muted)]">
              <span className="font-medium">Column Quick Toggles:</span>
              <div className="flex items-center gap-3">
                <button type="button" onClick={() => handleColumnToggleAll('canRead')} className="font-medium hover:text-[var(--tcx-primary)] hover:underline">
                  Toggle View
                </button>
                <span className="text-slate-300">·</span>
                <button type="button" onClick={() => handleColumnToggleAll('canCreate')} className="font-medium hover:text-[var(--tcx-primary)] hover:underline">
                  Toggle Create
                </button>
                <span className="text-slate-300">·</span>
                <button type="button" onClick={() => handleColumnToggleAll('canUpdate')} className="font-medium hover:text-[var(--tcx-primary)] hover:underline">
                  Toggle Edit
                </button>
                <span className="text-slate-300">·</span>
                <button type="button" onClick={() => handleColumnToggleAll('canDelete')} className="font-medium hover:text-[var(--tcx-primary)] hover:underline">
                  Toggle Delete
                </button>
                <span className="text-slate-300">·</span>
                <button type="button" onClick={() => handleColumnToggleAll('canExport')} className="font-medium hover:text-[var(--tcx-primary)] hover:underline">
                  Toggle Export
                </button>
              </div>
            </div>
          )}

          {/* Unified Permissions Table Matching Sidebar Order */}
          <div className="overflow-x-auto">
            <table className="w-full text-left text-[13px]">
              <thead>
                <tr className="border-b border-[var(--tcx-border)] text-[11px] font-bold uppercase tracking-wider text-[var(--tcx-muted)]">
                  <th className="py-2.5 px-4 w-[300px]">Module</th>
                  <th className="py-2.5 px-3 text-center w-[85px]">View</th>
                  <th className="py-2.5 px-3 text-center w-[85px]">Create</th>
                  <th className="py-2.5 px-3 text-center w-[85px]">Edit</th>
                  <th className="py-2.5 px-3 text-center w-[85px]">Delete</th>
                  <th className="py-2.5 px-3 text-center w-[85px]">Export</th>
                  <th className="py-2.5 px-3 text-center w-[75px]">All</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[var(--tcx-border)]">
                {SIDEBAR_MODULES.map((mod) => {
                  const meta = MODULE_META[mod];
                  const perm = matrix[mod] || { module: mod, canRead: false, canCreate: false, canUpdate: false, canDelete: false, canExport: false };
                  const isAllActive = perm.canRead && perm.canCreate && perm.canUpdate && perm.canDelete && perm.canExport;

                  return (
                    <tr key={mod} className="transition-colors hover:bg-[var(--tcx-surface-2)]/60">
                      <td className="py-3 px-4">
                        <div className="flex items-center gap-2.5">
                          <span className="grid h-7 w-7 flex-none place-items-center rounded-lg bg-[var(--tcx-surface-2)] text-[var(--tcx-primary)]">
                            <Icon name={meta.icon as IconName} size={15} />
                          </span>
                          <div>
                            <div className="font-semibold text-[13.5px] text-[var(--tcx-text)]">{meta.label}</div>
                            <div className="text-[11.5px] text-[var(--tcx-muted)]">{meta.description}</div>
                          </div>
                        </div>
                      </td>

                      <td className="py-3 px-3 text-center">
                        <Checkbox checked={perm.canRead} disabled={Boolean(editingRole?.isSystem)} onChange={() => handleCellToggle(mod, 'canRead')} />
                      </td>

                      <td className="py-3 px-3 text-center">
                        <Checkbox checked={perm.canCreate} disabled={Boolean(editingRole?.isSystem)} onChange={() => handleCellToggle(mod, 'canCreate')} />
                      </td>

                      <td className="py-3 px-3 text-center">
                        <Checkbox checked={perm.canUpdate} disabled={Boolean(editingRole?.isSystem)} onChange={() => handleCellToggle(mod, 'canUpdate')} />
                      </td>

                      <td className="py-3 px-3 text-center">
                        <Checkbox checked={perm.canDelete} disabled={Boolean(editingRole?.isSystem)} onChange={() => handleCellToggle(mod, 'canDelete')} />
                      </td>

                      <td className="py-3 px-3 text-center">
                        <Checkbox checked={perm.canExport} disabled={Boolean(editingRole?.isSystem)} onChange={() => handleCellToggle(mod, 'canExport')} />
                      </td>

                      <td className="py-3 px-3 text-center">
                        <Tooltip title={editingRole?.isSystem ? 'System roles have full access' : 'Toggle all actions for this module'}>
                          <Checkbox checked={isAllActive} disabled={Boolean(editingRole?.isSystem)} onChange={() => handleRowToggleAll(mod)} />
                        </Tooltip>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {/* Bottom Bar */}
          <div className="mt-6 flex items-center justify-between border-t border-[var(--tcx-border)] pt-4">
            <span className="text-[12.5px] text-[var(--tcx-muted)]">{editingRole?.isSystem ? 'System roles are managed by TechCMantix platform.' : 'Assigned users receive these permissions immediately upon saving.'}</span>
            <div className="flex items-center gap-2">
              <Button onClick={handleBackToList} disabled={saving}>
                {editingRole?.isSystem ? 'Back to Roles' : 'Cancel'}
              </Button>
              {!editingRole?.isSystem && (
                <Button type="primary" loading={saving} onClick={handleSaveRole} icon={<Icon name="shield" size={15} />}>
                  {editingRole ? 'Save Changes' : 'Create Role'}
                </Button>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // RENDER: CLEAN & INTUITIVE ROLES TABLE VIEW
  return (
    <div>
      <PageHeader
        eyebrow="USERS & ACCESS"
        title="Roles & Permissions"
        subtitle="Create custom roles manually and assign module-level CRUD permissions for your organization."
        actions={
          isAdmin ? (
            <Button type="primary" icon={<Icon name="plus" size={15} />} onClick={handleOpenCreate}>
              Create role
            </Button>
          ) : null
        }
      />

      {/* Standard CRM Stats Strip */}
      <div className="tcx-surface-card tcx-stats-strip">
        <div className="tcx-stat">
          <span>Total roles</span>
          <b>{totalRoles}</b>
        </div>
        <div className="tcx-stat">
          <span>Custom roles</span>
          <b className="text-blue-600">{customRolesCount}</b>
        </div>
        <div className="tcx-stat">
          <span>System roles</span>
          <b className="text-slate-600 dark:text-slate-300">{systemRolesCount}</b>
        </div>
        <div className="tcx-stat">
          <span>Assigned members</span>
          <b className="text-emerald-600">{totalAssignedUsers}</b>
        </div>
      </div>

      {/* Filter toolbar matching other CRM views */}
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-1 flex-wrap items-center gap-2">
          <Input
            allowClear
            prefix={<Icon name="search" size={15} />}
            placeholder="Search roles by name or description"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            className="w-full sm:!w-[280px]"
          />
          <Select
            value={typeFilter}
            onChange={(val) => {
              setTypeFilter(val);
              setPage(1);
            }}
            style={{ width: 160 }}
            options={[
              { label: 'All types', value: 'ALL' },
              { label: 'Custom roles', value: 'CUSTOM' },
              { label: 'System roles', value: 'SYSTEM' },
            ]}
          />
          {search || typeFilter !== 'ALL' ? (
            <Button
              type="text"
              size="small"
              onClick={() => {
                setSearch('');
                setTypeFilter('ALL');
                setPage(1);
              }}
            >
              Clear filters
            </Button>
          ) : null}
        </div>
      </div>

      {/* Reusable Standard CRM DataTable */}
      <DataTable<RoleRecord>
        columns={columns}
        data={pageRows}
        rowKey={(r) => r.id}
        loading={loading}
        emptyText={roles.length === 0 ? "No roles created yet. Click '+ Create role' to define your first custom role." : 'No roles match these filters.'}
        onRowClick={isAdmin ? (r) => handleOpenEdit(r) : undefined}
        pagination={{
          page: safePage,
          pageSize,
          total: filteredRoles.length,
          onPageChange: setPage,
        }}
      />
    </div>
  );
}
