import { useState, useEffect, useCallback, useRef } from 'react';
import { useOutletContext, useNavigate } from 'react-router-dom';
import {
  Table,
  Button,
  Input,
  Select,
  Tag,
  Space,
  Drawer,
  Form,
  InputNumber,
  Popconfirm,
  message,
  Row,
  Col,
  DatePicker,
  Modal,
  Badge,
  Grid,
  Divider,
  Tooltip,
  Spin,
  Collapse,
  Switch,
  Segmented,
  Alert,
  Typography,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  CheckOutlined,
  CloseOutlined,
  CloudSyncOutlined,
  SyncOutlined,
  LinkOutlined,
  DisconnectOutlined,
  SettingOutlined,
  UserAddOutlined,
  ContactsOutlined,
  DatabaseOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import { buildServiceUrl } from '@/lib/service-url';
import { useAuthStore } from '@/stores/auth.store';
import { getUserRoles } from '@/utils/roles';
import type {
  User,
  UserRole,
  UserStatus,
  UsersListResponse,
  UsersListParams,
  CreateUserPayload,
  UpdateUserPayload,
  AppOutletContext,
  ServiceProvisioningStatus,
  ProvisioningStatusResponse,
  ProvisionAllResult,
  SiteSettings,
  LinkedContactResponse,
  Contact,
  SupportLevel,
  ServicesConfig,
} from '@/types/api';
import { SUPPORT_LEVEL_LABELS, SUPPORT_LEVEL_COLORS, CONTACT_SOURCE_LABELS, CONTACT_SOURCE_COLORS } from '@/types/api';
import { PageTour } from '@/components/tour/PageTour';


const roleColors: Record<UserRole, string> = {
  SUPER_ADMIN: 'red',
  INFLUENCE_ADMIN: 'volcano',
  MAP_ADMIN: 'orange',
  BROADCAST_ADMIN: 'gold',
  CONTENT_ADMIN: 'lime',
  MEDIA_ADMIN: 'purple',
  PAYMENTS_ADMIN: 'green',
  EVENTS_ADMIN: 'cyan',
  SOCIAL_ADMIN: 'magenta',
  POLLS_ADMIN: 'geekblue',
  ANALYTICS_ADMIN: 'processing',
  USER: 'blue',
  TEMP: 'default',
};

const statusColors: Record<UserStatus, string> = {
  ACTIVE: 'green',
  INACTIVE: 'default',
  SUSPENDED: 'red',
  EXPIRED: 'orange',
  PENDING_VERIFICATION: 'purple',
  PENDING_APPROVAL: 'gold',
};

const roleOptions: { value: UserRole; label: string }[] = [
  { value: 'SUPER_ADMIN', label: 'Super Admin' },
  { value: 'INFLUENCE_ADMIN', label: 'Advocacy Admin' },
  { value: 'MAP_ADMIN', label: 'Map Admin' },
  { value: 'BROADCAST_ADMIN', label: 'Broadcast Admin' },
  { value: 'CONTENT_ADMIN', label: 'Content Admin' },
  { value: 'MEDIA_ADMIN', label: 'Media Admin' },
  { value: 'PAYMENTS_ADMIN', label: 'Payments Admin' },
  { value: 'EVENTS_ADMIN', label: 'Events Admin' },
  { value: 'SOCIAL_ADMIN', label: 'Social Admin' },
  { value: 'USER', label: 'User' },
  { value: 'TEMP', label: 'Temp' },
];

const statusOptions: { value: UserStatus; label: string }[] = [
  { value: 'ACTIVE', label: 'Active' },
  { value: 'INACTIVE', label: 'Inactive' },
  { value: 'SUSPENDED', label: 'Suspended' },
  { value: 'EXPIRED', label: 'Expired' },
  { value: 'PENDING_VERIFICATION', label: 'Pending Verification' },
  { value: 'PENDING_APPROVAL', label: 'Pending Approval' },
];

export default function UsersPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { user: currentUser } = useAuthStore();
  const isSuperAdmin = currentUser ? getUserRoles(currentUser).includes('SUPER_ADMIN') : false;
  const [nocodbUrl, setNocodbUrl] = useState<string | null>(null);
  const [users, setUsers] = useState<User[]>([]);
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  const [roleFilter, setRoleFilter] = useState<UserRole | undefined>();
  const [statusFilter, setStatusFilter] = useState<UserStatus | undefined>();
  const [createDrawerOpen, setCreateDrawerOpen] = useState(false);
  const [editDrawerOpen, setEditDrawerOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [rejectModalOpen, setRejectModalOpen] = useState(false);
  const [rejectingUser, setRejectingUser] = useState<User | null>(null);
  const [rejectReason, setRejectReason] = useState('');
  const [provisioningStatuses, setProvisioningStatuses] = useState<ServiceProvisioningStatus[]>([]);
  const [provisioningLoading, setProvisioningLoading] = useState(false);
  const [provisionAllLoading, setProvisionAllLoading] = useState(false);
  const [provSettings, setProvSettings] = useState<Partial<SiteSettings>>({});
  const navigate = useNavigate();
  const [linkedContact, setLinkedContact] = useState<Contact | null>(null);
  const [linkedContactLoading, setLinkedContactLoading] = useState(false);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  useEffect(() => {
    if (isSuperAdmin) {
      api.get<ServicesConfig>('/services/config')
        .then(({ data }) => setNocodbUrl(buildServiceUrl(data.nocodbSubdomain, data.domain, data.nocodbPort)))
        .catch(() => {});
    }
  }, [isSuperAdmin]);

  useEffect(() => {
    setPageHeader({
      title: 'Users',
      actions: isSuperAdmin && nocodbUrl ? (
        <Tooltip title="Browse users in NocoDB for advanced filtering & export">
          <Button icon={<DatabaseOutlined />} href={nocodbUrl} target="_blank" size="small">
            Browse in NocoDB
          </Button>
        </Tooltip>
      ) : undefined,
    });
    return () => setPageHeader(null);
  }, [setPageHeader, isSuperAdmin, nocodbUrl]);

  const getActiveDrawerWidth = () => {
    if (createDrawerOpen) return 520;
    if (editDrawerOpen) return 520;
    return 0;
  };

  const activeDrawerWidth = getActiveDrawerWidth();

  const handleSearchChange = (value: string) => {
    setSearch(value);
    clearTimeout(searchTimerRef.current);
    searchTimerRef.current = setTimeout(() => setDebouncedSearch(value), 300);
  };

  useEffect(() => {
    return () => clearTimeout(searchTimerRef.current);
  }, []);

  const fetchUsers = useCallback(async (params?: UsersListParams) => {
    setLoading(true);
    try {
      const { data } = await api.get<UsersListResponse>('/users', {
        params: {
          page: params?.page ?? pagination.page,
          limit: params?.limit ?? pagination.limit,
          search: params?.search ?? (debouncedSearch || undefined),
          role: params?.role ?? roleFilter,
          status: params?.status ?? statusFilter,
        },
      });
      setUsers(data.users);
      setPagination(data.pagination);
    } catch {
      message.error('Failed to load users');
    } finally {
      setLoading(false);
    }
  }, [pagination.page, pagination.limit, debouncedSearch, roleFilter, statusFilter]);

  useEffect(() => {
    fetchUsers({ page: 1 });
  }, [debouncedSearch, roleFilter, statusFilter]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleTableChange = (pag: TablePaginationConfig) => {
    fetchUsers({ page: pag.current ?? 1, limit: pag.pageSize ?? 20 });
  };

  const handleCreate = async (values: CreateUserPayload & { expiresAtDate?: dayjs.Dayjs }) => {
    try {
      const payload: CreateUserPayload = { ...values };
      if (values.expiresAtDate) {
        payload.expiresAt = values.expiresAtDate.toISOString();
      }
      delete (payload as unknown as Record<string, unknown>).expiresAtDate;
      await api.post('/users', payload);
      message.success('User created');
      setCreateDrawerOpen(false);
      createForm.resetFields();
      fetchUsers({ page: 1 });
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: { message?: string } } } })
          ?.response?.data?.error?.message || 'Failed to create user';
      message.error(msg);
    }
  };

  const handleEdit = async (values: UpdateUserPayload & { expiresAtDate?: dayjs.Dayjs | null; canManageUsers?: boolean }) => {
    if (!editingUser) return;
    try {
      const payload: UpdateUserPayload = { ...values };
      if (values.expiresAtDate) {
        payload.expiresAt = values.expiresAtDate.toISOString();
      } else if (values.expiresAtDate === null) {
        payload.expiresAt = null;
      }
      delete (payload as unknown as Record<string, unknown>).expiresAtDate;
      // Merge canManageUsers into permissions
      if (isSuperAdmin && values.canManageUsers !== undefined) {
        const existingPerms = (editingUser.permissions as Record<string, unknown>) || {};
        (payload as unknown as Record<string, unknown>).permissions = {
          ...existingPerms,
          canManageUsers: values.canManageUsers,
        };
      }
      delete (payload as unknown as Record<string, unknown>).canManageUsers;
      // Remove empty password
      if (!payload.password) delete payload.password;
      await api.put(`/users/${editingUser.id}`, payload);
      message.success('User updated');
      setEditDrawerOpen(false);
      setEditingUser(null);
      editForm.resetFields();
      fetchUsers();
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: { message?: string } } } })
          ?.response?.data?.error?.message || 'Failed to update user';
      message.error(msg);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/users/${id}`);
      message.success('User deleted');
      fetchUsers();
    } catch {
      message.error('Failed to delete user');
    }
  };

  const handleApprove = async (user: User) => {
    try {
      await api.post(`/users/${user.id}/approve`);
      message.success(`${user.name || user.email} approved`);
      fetchUsers();
    } catch {
      message.error('Failed to approve user');
    }
  };

  const handleReject = async () => {
    if (!rejectingUser) return;
    try {
      await api.post(`/users/${rejectingUser.id}/reject`, {
        reason: rejectReason || undefined,
      });
      message.success(`${rejectingUser.name || rejectingUser.email} rejected`);
      setRejectModalOpen(false);
      setRejectingUser(null);
      setRejectReason('');
      fetchUsers();
    } catch {
      message.error('Failed to reject user');
    }
  };

  const fetchProvisioningStatus = useCallback(async (userId: string) => {
    setProvisioningLoading(true);
    try {
      const { data } = await api.get<ProvisioningStatusResponse>(`/users/${userId}/provisioning`);
      setProvisioningStatuses(data.services);
    } catch {
      setProvisioningStatuses([]);
    } finally {
      setProvisioningLoading(false);
    }
  }, []);

  const fetchProvSettings = useCallback(async () => {
    try {
      const { data } = await api.get<SiteSettings>('/settings');
      setProvSettings(data);
    } catch { /* ignore */ }
  }, []);

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

  const fetchLinkedContact = useCallback(async (userId: string) => {
    setLinkedContactLoading(true);
    try {
      const { data } = await api.get<LinkedContactResponse>(`/users/${userId}/contact`);
      setLinkedContact(data.contact);
    } catch {
      setLinkedContact(null);
    } finally {
      setLinkedContactLoading(false);
    }
  }, []);

  const updateProvSetting = async (field: string, value: unknown) => {
    try {
      await api.put('/settings', { [field]: value });
      setProvSettings(prev => ({ ...prev, [field]: value }));
    } catch {
      message.error('Failed to update setting');
    }
  };

  const handleProvision = async (userId: string, serviceKey: string) => {
    try {
      await api.post(`/users/${userId}/provisioning/${serviceKey}`);
      message.success(`Provisioned to ${serviceKey}`);
      fetchProvisioningStatus(userId);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })
        ?.response?.data?.error?.message || 'Provisioning failed';
      message.error(msg);
    }
  };

  const handleDeprovision = async (userId: string, serviceKey: string) => {
    try {
      await api.delete(`/users/${userId}/provisioning/${serviceKey}`);
      message.success(`Deprovisioned from ${serviceKey}`);
      fetchProvisioningStatus(userId);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })
        ?.response?.data?.error?.message || 'Deprovisioning failed';
      message.error(msg);
    }
  };

  const handleProvisionAll = async (userId: string) => {
    setProvisionAllLoading(true);
    try {
      const { data } = await api.post<ProvisionAllResult>(`/users/${userId}/provisioning/provision-all`);
      const succeeded = data.results.filter(r => r.success);
      const failed = data.results.filter(r => !r.success);
      if (failed.length === 0 && succeeded.length > 0) {
        message.success(`Provisioned to ${succeeded.map(r => r.displayName).join(', ')}`);
      } else if (succeeded.length > 0 && failed.length > 0) {
        message.warning(`Provisioned to ${succeeded.map(r => r.displayName).join(', ')}. Failed: ${failed.map(r => `${r.displayName} (${r.error})`).join(', ')}`);
      } else if (failed.length > 0) {
        message.error(`Provisioning failed: ${failed.map(r => `${r.displayName} (${r.error})`).join(', ')}`);
      } else {
        message.info('No services to provision');
      }
      fetchProvisioningStatus(userId);
    } catch {
      message.error('Provision all failed');
    } finally {
      setProvisionAllLoading(false);
    }
  };

  const openEdit = (user: User) => {
    setEditingUser(user);
    const roles = getUserRoles(user);
    editForm.setFieldsValue({
      email: user.email,
      name: user.name,
      phone: user.phone,
      role: user.role,
      roles,
      status: user.status,
      expireDays: user.expireDays,
      expiresAtDate: user.expiresAt ? dayjs(user.expiresAt) : null,
      canManageUsers: !!(user.permissions as Record<string, unknown> | undefined)?.canManageUsers,
    });
    setEditDrawerOpen(true);
    fetchProvisioningStatus(user.id);
    fetchLinkedContact(user.id);
  };

  // Count pending approval users
  const pendingCount = users.filter(u => u.status === 'PENDING_APPROVAL').length;

  const columns: ColumnsType<User> = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (name: string | null) => name || '--',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'Roles',
      key: 'roles',
      responsive: ['md'] as any,
      render: (_: unknown, record: User) => {
        const roles = getUserRoles(record);
        return (
          <Space size={2} wrap>
            {roles.map((r) => (
              <Tag key={r} color={roleColors[r]}>{r.replace(/_/g, ' ')}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      onHeaderCell: () => ({ 'data-tour-users-status': true } as Record<string, unknown>),
      render: (status: UserStatus) => (
        <Tag color={statusColors[status]}>{status.replace(/_/g, ' ')}</Tag>
      ),
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => dayjs(date).format('YYYY-MM-DD'),
      responsive: ['md'],
    },
    {
      title: 'Last Login',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      render: (date: string | null) =>
        date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '--',
      responsive: ['lg'],
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, record: User) => (
        <Space>
          {record.status === 'PENDING_APPROVAL' && (
            <>
              <Popconfirm
                title="Approve this user?"
                description="They will be able to log in."
                onConfirm={() => handleApprove(record)}
              >
                <Button type="link" size="small" icon={<CheckOutlined />} style={{ color: '#52c41a' }} />
              </Popconfirm>
              <Button
                type="link"
                size="small"
                danger
                icon={<CloseOutlined />}
                onClick={() => {
                  setRejectingUser(record);
                  setRejectReason('');
                  setRejectModalOpen(true);
                }}
              />
            </>
          )}
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => openEdit(record)}
          />
          <Popconfirm
            title="Delete this user?"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const createRoleValue = Form.useWatch('role', createForm);
  const editRoleValue = Form.useWatch('role', editForm);

  return (
    <>
      {/* Main Content Container - shifts when drawer opens */}
      <div
        style={{
          marginRight: isMobile ? 0 : activeDrawerWidth,
          transition: 'margin-right 0.15s cubic-bezier(0.2, 0, 0, 1)',
        }}
      >
        <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
          <Col>
            {pendingCount > 0 && (
              <Badge count={pendingCount} style={{ backgroundColor: '#faad14' }} />
            )}
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setCreateDrawerOpen(true)}
              data-tour-users-create
            >
              Create User
            </Button>
          </Col>
        </Row>

        <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
          <Col xs={24} sm={10} md={8}>
            <Input
              placeholder="Search by name or email"
              prefix={<SearchOutlined />}
              value={search}
              onChange={(e) => handleSearchChange(e.target.value)}
              allowClear
            />
          </Col>
          <Col xs={12} sm={7} md={4}>
            <Select
              placeholder="Role"
              options={roleOptions}
              value={roleFilter}
              onChange={setRoleFilter}
              allowClear
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={12} sm={7} md={4}>
            <Select
              placeholder="Status"
              options={statusOptions}
              value={statusFilter}
              onChange={setStatusFilter}
              allowClear
              style={{ width: '100%' }}
            />
          </Col>
        </Row>

        <Collapse
          size="small"
          style={{ marginBottom: 16 }}
          items={[{
            key: 'provisioning',
            label: (
              <Space size={6}>
                <SettingOutlined />
                <span>User Provisioning</span>
                {provSettings.enableUserProvisioning && <Tag color="green" style={{ margin: 0, fontSize: 10 }}>Active</Tag>}
              </Space>
            ),
            children: (
              <div style={{ maxWidth: 560 }}>
                <Alert
                  type="info"
                  message="Lazy = provision on first access. Eager = provision immediately on user creation."
                  showIcon
                  style={{ marginBottom: 16 }}
                />
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                  <div>
                    <div style={{ fontWeight: 500 }}>Enable User Provisioning</div>
                    <div style={{ fontSize: 12, color: '#888' }}>Master toggle for automatic provisioning</div>
                  </div>
                  <Switch
                    checked={!!provSettings.enableUserProvisioning}
                    onChange={(v) => updateProvSetting('enableUserProvisioning', v)}
                  />
                </div>
                <Divider orientation="left" style={{ fontSize: 13, margin: '12px 0' }}>Gitea</Divider>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <div>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>Provision to Gitea</div>
                    <div style={{ fontSize: 11, color: '#888' }}>Create Gitea accounts (requires admin API token)</div>
                  </div>
                  <Switch
                    size="small"
                    checked={!!provSettings.provisionGitea}
                    onChange={(v) => updateProvSetting('provisionGitea', v)}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <span style={{ fontSize: 12, color: '#888' }}>Timing:</span>
                  <Segmented
                    size="small"
                    value={provSettings.provisionGiteaTiming || 'lazy'}
                    options={[{ value: 'lazy', label: 'Lazy' }, { value: 'eager', label: 'Eager' }]}
                    onChange={(v) => updateProvSetting('provisionGiteaTiming', v)}
                  />
                </div>
                <Divider orientation="left" style={{ fontSize: 13, margin: '12px 0' }}>Vaultwarden</Divider>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <div>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>Provision to Vaultwarden</div>
                    <div style={{ fontSize: 11, color: '#888' }}>Invite emails (users set own master password)</div>
                  </div>
                  <Switch
                    size="small"
                    checked={!!provSettings.provisionVaultwarden}
                    onChange={(v) => updateProvSetting('provisionVaultwarden', v)}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <span style={{ fontSize: 12, color: '#888' }}>Timing:</span>
                  <Segmented
                    size="small"
                    value={provSettings.provisionVaultwardenTiming || 'lazy'}
                    options={[{ value: 'lazy', label: 'Lazy' }, { value: 'eager', label: 'Eager' }]}
                    onChange={(v) => updateProvSetting('provisionVaultwardenTiming', v)}
                  />
                </div>
                <Divider orientation="left" style={{ fontSize: 13, margin: '12px 0' }}>Listmonk</Divider>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <div>
                    <div style={{ fontWeight: 500, fontSize: 13 }}>Provision to Listmonk</div>
                    <div style={{ fontSize: 11, color: '#888' }}>Add users as subscribers to newsletter lists</div>
                  </div>
                  <Switch
                    size="small"
                    checked={!!provSettings.provisionListmonk}
                    onChange={(v) => updateProvSetting('provisionListmonk', v)}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <span style={{ fontSize: 12, color: '#888' }}>Timing:</span>
                  <Segmented
                    size="small"
                    value={provSettings.provisionListmonkTiming || 'eager'}
                    options={[{ value: 'lazy', label: 'Lazy' }, { value: 'eager', label: 'Eager' }]}
                    onChange={(v) => updateProvSetting('provisionListmonkTiming', v)}
                  />
                </div>
                <Divider orientation="left" style={{ fontSize: 13, margin: '12px 0' }}>Rocket.Chat</Divider>
                <Alert
                  type="warning"
                  message="Rocket.Chat provisioning is always lazy (SSO on first access). Controlled by the 'Enable Team Chat' toggle in Settings."
                  style={{ marginBottom: 0 }}
                />
              </div>
            ),
          }, {
            key: 'registration',
            label: (
              <Space size={6}>
                <UserAddOutlined />
                <span>Registration</span>
                {provSettings.enablePublicRegistration && <Tag color="green" style={{ margin: 0, fontSize: 10 }}>Open</Tag>}
              </Space>
            ),
            children: (
              <div style={{ maxWidth: 560 }}>
                <Alert
                  type="info"
                  message="Controls the self-registration flow for new users on the login page."
                  showIcon
                  style={{ marginBottom: 16 }}
                />
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                  <div>
                    <div style={{ fontWeight: 500 }}>Enable Public Registration</div>
                    <div style={{ fontSize: 12, color: '#888' }}>Allow new users to register on the login page</div>
                  </div>
                  <Switch
                    checked={!!provSettings.enablePublicRegistration}
                    onChange={(v) => updateProvSetting('enablePublicRegistration', v)}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                  <div>
                    <div style={{ fontWeight: 500 }}>Require Email Verification</div>
                    <div style={{ fontSize: 12, color: '#888' }}>Must verify email before accessing the system (requires SMTP)</div>
                  </div>
                  <Switch
                    checked={!!provSettings.enableEmailVerification}
                    onChange={(v) => updateProvSetting('enableEmailVerification', v)}
                  />
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ fontWeight: 500 }}>Auto-Approve Verified Users</div>
                    <div style={{ fontSize: 12, color: '#888' }}>When disabled, an admin must manually approve each verified user</div>
                  </div>
                  <Switch
                    checked={!!provSettings.autoApproveVerifiedUsers}
                    onChange={(v) => updateProvSetting('autoApproveVerifiedUsers', v)}
                  />
                </div>
              </div>
            ),
          }]}
        />

        <div data-tour-users-table>
          <Table<User>
            columns={columns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            pagination={{
              current: pagination.page,
              pageSize: pagination.limit,
              total: pagination.total,
              showSizeChanger: true,
              showTotal: (total) => `${total} users`,
            }}
            onChange={handleTableChange}
            scroll={{ x: 'max-content' }}
            locale={{ emptyText: 'No users found' }}
          />
        </div>
      </div>

      {/* Create Drawer */}
      <Drawer
        title="Create User"
        open={createDrawerOpen}
        placement="right"
        width={isMobile ? '100%' : 520}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        onClose={() => {
          setCreateDrawerOpen(false);
          createForm.resetFields();
        }}
        extra={
          <Space>
            <Button onClick={() => {
              setCreateDrawerOpen(false);
              createForm.resetFields();
            }}>
              Cancel
            </Button>
            <Button type="primary" onClick={() => createForm.submit()}>
              Create User
            </Button>
          </Space>
        }
      >
        <Form form={createForm} onFinish={handleCreate} layout="vertical">
          <Form.Item
            name="email"
            label="Email"
            rules={[
              { required: true, message: 'Email is required' },
              { type: 'email', message: 'Invalid email' },
            ]}
          >
            <Input placeholder="jane@example.com" />
          </Form.Item>
          <Form.Item
            name="password"
            label="Password"
            rules={[
              { required: true, message: 'Password is required' },
              { min: 8, message: 'Minimum 8 characters' },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item name="name" label="Name">
            <Input placeholder="Full Name" />
          </Form.Item>
          <Form.Item name="phone" label="Phone">
            <Input placeholder="+1 555 000 0000" />
          </Form.Item>
          <Form.Item name="pronouns" label="Pronouns">
            <Input placeholder="e.g., they/them, she/her, he/him" />
          </Form.Item>
          <Form.Item name="roles" label="Roles" initialValue={['USER']}>
            <Select
              mode="multiple"
              options={roleOptions}
              placeholder="Select roles"
            />
          </Form.Item>
          <Row gutter={12}>
            <Col span={12}>
              <Form.Item name="role" label="Primary Role" initialValue="USER">
                <Select options={roleOptions} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="Status" initialValue="ACTIVE">
                <Select options={statusOptions} />
              </Form.Item>
            </Col>
          </Row>
          {createRoleValue === 'TEMP' && (
            <Row gutter={12}>
              <Col span={12}>
                <Form.Item name="expiresAtDate" label="Expires At">
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="expireDays" label="Expire Days">
                  <InputNumber min={1} style={{ width: '100%' }} />
                </Form.Item>
              </Col>
            </Row>
          )}
        </Form>
      </Drawer>

      {/* Edit Drawer */}
      <Drawer
        title="Edit User"
        open={editDrawerOpen}
        placement="right"
        width={isMobile ? '100%' : 520}
        mask={false}
        destroyOnHidden
        rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
        onClose={() => {
          setEditDrawerOpen(false);
          setEditingUser(null);
          editForm.resetFields();
        }}
        extra={
          <Space>
            <Button onClick={() => {
              setEditDrawerOpen(false);
              setEditingUser(null);
              editForm.resetFields();
            }}>
              Cancel
            </Button>
            <Button type="primary" onClick={() => editForm.submit()}>
              Save Changes
            </Button>
          </Space>
        }
      >
        <Form form={editForm} onFinish={handleEdit} layout="vertical">
          <Form.Item
            name="email"
            label="Email"
            rules={[
              { required: true, message: 'Email is required' },
              { type: 'email', message: 'Invalid email' },
            ]}
          >
            <Input placeholder="jane@example.com" />
          </Form.Item>
          <Form.Item
            name="password"
            label="Password"
            help="Leave blank to keep current password"
          >
            <Input.Password />
          </Form.Item>
          <Form.Item name="name" label="Name">
            <Input placeholder="Full Name" />
          </Form.Item>
          <Form.Item name="phone" label="Phone">
            <Input placeholder="+1 555 000 0000" />
          </Form.Item>
          <Form.Item name="pronouns" label="Pronouns">
            <Input placeholder="e.g., they/them, she/her, he/him" />
          </Form.Item>
          <Form.Item name="roles" label="Roles">
            <Select
              mode="multiple"
              options={roleOptions}
              placeholder="Select roles"
            />
          </Form.Item>
          <Row gutter={12}>
            <Col span={12}>
              <Form.Item name="role" label="Primary Role">
                <Select options={roleOptions} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="Status">
                <Select options={statusOptions} />
              </Form.Item>
            </Col>
          </Row>
          {editRoleValue === 'TEMP' && (
            <Row gutter={12}>
              <Col span={12}>
                <Form.Item name="expiresAtDate" label="Expires At">
                  <DatePicker style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="expireDays" label="Expire Days">
                  <InputNumber min={1} style={{ width: '100%' }} />
                </Form.Item>
              </Col>
            </Row>
          )}
          {isSuperAdmin && (
            <Form.Item
              name="canManageUsers"
              label="Can Manage Users"
              valuePropName="checked"
              help="Allows this admin to create, edit, and delete users"
            >
              <Switch />
            </Form.Item>
          )}
        </Form>

        {editingUser && (
          <>
            {/* Linked Contact Panel */}
            <Divider style={{ margin: '16px 0 12px' }}>
              <Space size={4}>
                <ContactsOutlined />
                Linked Contact
              </Space>
            </Divider>

            {linkedContactLoading ? (
              <div style={{ textAlign: 'center', padding: 8 }}><Spin size="small" /></div>
            ) : linkedContact ? (
              <div
                style={{
                  padding: '10px 12px',
                  background: 'rgba(255,255,255,0.04)',
                  borderRadius: 6,
                  border: '1px solid rgba(255,255,255,0.08)',
                  marginBottom: 8,
                }}
              >
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <Typography.Text strong style={{ fontSize: 14 }}>{linkedContact.displayName}</Typography.Text>
                  <Button size="small" type="link" onClick={() => navigate('/app/people')}>
                    View in People
                  </Button>
                </div>
                <Space size={4} wrap style={{ marginBottom: 4 }}>
                  <Tag color={CONTACT_SOURCE_COLORS[linkedContact.primarySource]} style={{ margin: 0, fontSize: 11 }}>
                    {CONTACT_SOURCE_LABELS[linkedContact.primarySource]}
                  </Tag>
                  {linkedContact.supportLevel && (
                    <Tag
                      color={SUPPORT_LEVEL_COLORS[linkedContact.supportLevel as SupportLevel]}
                      style={{ margin: 0, fontSize: 11 }}
                    >
                      {SUPPORT_LEVEL_LABELS[linkedContact.supportLevel as SupportLevel]}
                    </Tag>
                  )}
                  {linkedContact.tags?.map((t) => (
                    <Tag key={t} style={{ margin: 0, fontSize: 11 }}>{t}</Tag>
                  ))}
                </Space>
                {linkedContact.email && linkedContact.email !== editingUser.email && (
                  <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)', marginTop: 2 }}>
                    Contact email: {linkedContact.email}
                  </div>
                )}
              </div>
            ) : (
              <div style={{ color: '#888', fontSize: 13, textAlign: 'center', padding: 8 }}>
                No linked contact
              </div>
            )}

            <Divider style={{ margin: '16px 0 12px' }}>
              <Space size={4}>
                <CloudSyncOutlined />
                Service Accounts
              </Space>
            </Divider>

            {!provisioningLoading && provisioningStatuses.some(s => s.status === 'not_provisioned' || s.status === 'error') && (
              <div style={{ marginBottom: 8 }}>
                <Button
                  type="primary"
                  size="small"
                  icon={<CloudSyncOutlined />}
                  loading={provisionAllLoading}
                  onClick={() => handleProvisionAll(editingUser.id)}
                  block
                >
                  Provision All Services
                </Button>
              </div>
            )}

            {provisioningLoading ? (
              <div style={{ textAlign: 'center', padding: 16 }}><Spin size="small" /></div>
            ) : provisioningStatuses.length === 0 ? (
              <div style={{ color: '#888', fontSize: 13, textAlign: 'center', padding: 8 }}>
                No provisioning services configured
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {provisioningStatuses.map((svc) => {
                  const provisionStatusMap = new Map([
                    ['synced', { color: 'green', label: 'Synced' }],
                    ['pending', { color: 'processing', label: 'Pending' }],
                    ['error', { color: 'red', label: 'Error' }],
                    ['not_provisioned', { color: 'default', label: 'Not Provisioned' }],
                    ['invited', { color: 'purple', label: 'Invited' }],
                  ]);
                  const cfg = provisionStatusMap.get(svc.status) || { color: 'default', label: 'Unknown' };

                  return (
                    <div
                      key={svc.serviceKey}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        padding: '6px 10px',
                        background: 'rgba(255,255,255,0.04)',
                        borderRadius: 6,
                        border: '1px solid rgba(255,255,255,0.08)',
                      }}
                    >
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 13 }}>{svc.displayName}</div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                          <Tag color={cfg.color} style={{ margin: 0, fontSize: 11 }}>{cfg.label}</Tag>
                          {svc.serviceUserId && (
                            <span style={{ fontSize: 11, color: '#888' }}>
                              ID: {svc.serviceUserId}
                            </span>
                          )}
                          {svc.details?.username != null && (
                            <span style={{ fontSize: 11, color: '#888' }}>
                              @{String(svc.details.username)}
                            </span>
                          )}
                        </div>
                        {svc.lastError && (
                          <Tooltip title={svc.lastError}>
                            <span style={{ fontSize: 11, color: '#ff4d4f', cursor: 'help' }}>
                              {svc.lastError.slice(0, 40)}{svc.lastError.length > 40 ? '...' : ''}
                            </span>
                          </Tooltip>
                        )}
                      </div>
                      <Space size={4}>
                        {(svc.status === 'not_provisioned' || svc.status === 'error') && (
                          <Tooltip title="Provision">
                            <Button
                              type="text"
                              size="small"
                              icon={<LinkOutlined />}
                              onClick={() => handleProvision(editingUser.id, svc.serviceKey)}
                            />
                          </Tooltip>
                        )}
                        {svc.status === 'synced' && (
                          <>
                            <Tooltip title="Re-sync">
                              <Button
                                type="text"
                                size="small"
                                icon={<SyncOutlined />}
                                onClick={() => handleProvision(editingUser.id, svc.serviceKey)}
                              />
                            </Tooltip>
                            <Popconfirm
                              title={`Deprovision from ${svc.displayName}?`}
                              onConfirm={() => handleDeprovision(editingUser.id, svc.serviceKey)}
                            >
                              <Tooltip title="Deprovision">
                                <Button type="text" size="small" danger icon={<DisconnectOutlined />} />
                              </Tooltip>
                            </Popconfirm>
                          </>
                        )}
                        {svc.status === 'invited' && (
                          <Tooltip title="Re-invite">
                            <Button
                              type="text"
                              size="small"
                              icon={<SyncOutlined />}
                              onClick={() => handleProvision(editingUser.id, svc.serviceKey)}
                            />
                          </Tooltip>
                        )}
                      </Space>
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}
      </Drawer>

      {/* Reject Modal */}
      <Modal
        title={`Reject ${rejectingUser?.name || rejectingUser?.email || 'User'}?`}
        open={rejectModalOpen}
        onCancel={() => {
          setRejectModalOpen(false);
          setRejectingUser(null);
          setRejectReason('');
        }}
        onOk={handleReject}
        okText="Reject"
        okButtonProps={{ danger: true }}
      >
        <Input.TextArea
          placeholder="Optional reason for rejection"
          value={rejectReason}
          onChange={(e) => setRejectReason(e.target.value)}
          rows={3}
        />
      </Modal>
      <PageTour sectionId="user-management" />
    </>
  );
}
