import React, { useState, useEffect, useCallback } from 'react';
import { Shield, Clock, Activity, Plus, Edit2, Trash2, Loader, AlertCircle, CheckCircle, X, ChevronLeft, ChevronRight, Search, Users, FileText } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import ConfirmModal from '../ConfirmModal';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';

const TABS = [
  { id: 'users',  label: 'User Management', icon: Shield },
  { id: 'audit',  label: 'Audit Log',       icon: Clock },
  { id: 'system', label: 'System Info',      icon: Activity },
];

// ---------------------------------------------------------------------------
// Themed group badge colors (exported for property testing)
// ---------------------------------------------------------------------------
export const GROUP_BADGE_THEMED = {
  Admin:         { bg: 'rgba(239,68,68,0.15)',  border: '#EF4444', text: '#FCA5A5' },
  Standard_User: { bg: 'rgba(14,165,233,0.15)', border: '#0EA5E9', text: '#7DD3FC' },
  Leadership:    { bg: 'rgba(245,158,11,0.15)', border: '#F59E0B', text: '#FCD34D' },
  Read_Only:     { bg: 'rgba(148,163,184,0.15)', border: '#94A3B8', text: '#CBD5E1' },
};

const DEFAULT_GROUP_BADGE_STYLE = { bg: 'rgba(148,163,184,0.15)', border: '#94A3B8', text: '#CBD5E1' };

// ---------------------------------------------------------------------------
// Themed action badge colors (exported for property testing)
// ---------------------------------------------------------------------------
export const ACTION_BADGE_THEMED = {
  login:           { bg: 'rgba(16,185,129,0.15)',  border: '#10B981', text: '#6EE7B7' },
  logout:          { bg: 'rgba(148,163,184,0.15)', border: '#94A3B8', text: '#CBD5E1' },
  login_failed:    { bg: 'rgba(239,68,68,0.15)',   border: '#EF4444', text: '#FCA5A5' },
  user_create:     { bg: 'rgba(14,165,233,0.15)',  border: '#0EA5E9', text: '#7DD3FC' },
  user_update:     { bg: 'rgba(245,158,11,0.15)',  border: '#F59E0B', text: '#FCD34D' },
  user_delete:     { bg: 'rgba(239,68,68,0.15)',   border: '#EF4444', text: '#FCA5A5' },
  cve_create:      { bg: 'rgba(14,165,233,0.15)',  border: '#0EA5E9', text: '#7DD3FC' },
  cve_edit:        { bg: 'rgba(245,158,11,0.15)',  border: '#F59E0B', text: '#FCD34D' },
  cve_delete:      { bg: 'rgba(239,68,68,0.15)',   border: '#EF4444', text: '#FCA5A5' },
  document_upload: { bg: 'rgba(139,92,246,0.15)',  border: '#8B5CF6', text: '#C4B5FD' },
  document_delete: { bg: 'rgba(239,68,68,0.15)',   border: '#EF4444', text: '#FCA5A5' },
};

const DEFAULT_ACTION_BADGE_STYLE = { bg: 'rgba(148,163,184,0.15)', border: '#94A3B8', text: '#CBD5E1' };

/**
 * Returns themed badge style for an audit log action.
 * Falls back to muted styling for unknown actions.
 */
export function getActionBadgeStyle(action) {
  return ACTION_BADGE_THEMED[action] || DEFAULT_ACTION_BADGE_STYLE;
}

/**
 * Returns themed badge style for a user group.
 * Falls back to muted styling for unknown groups.
 */
export function getGroupBadgeStyle(group) {
  return GROUP_BADGE_THEMED[group] || DEFAULT_GROUP_BADGE_STYLE;
}

/**
 * Builds edit-form data from a user object.
 * Password is always blank when editing.
 */
export function buildEditFormData(user) {
  return {
    username: user.username,
    email: user.email,
    password: '',
    group: user.group,
  };
}

/**
 * Determines whether self-modification controls should be disabled.
 * Returns true when the row user is the currently authenticated user.
 */
export function isSelfUser(currentUserId, rowUserId) {
  return currentUserId != null && rowUserId != null && String(currentUserId) === String(rowUserId);
}

/**
 * Computes the number of users who logged in within the last 7 days.
 * Exported for property testing.
 */
export function computeRecentLogins(users, now = new Date()) {
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  return users.filter(u => {
    if (!u.last_login) return false;
    const loginDate = new Date(u.last_login);
    return loginDate >= sevenDaysAgo && loginDate <= now;
  }).length;
}

const VALID_GROUPS = ['Admin', 'Standard_User', 'Leadership', 'Read_Only'];

const GROUP_LABELS = {
  Admin: 'Admin',
  Standard_User: 'Standard User',
  Leadership: 'Leadership',
  Read_Only: 'Read Only',
};

// ---------------------------------------------------------------------------
// UserManagementPanel
// ---------------------------------------------------------------------------
function UserManagementPanel() {
  const { user: currentUser } = useAuth();

  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [formData, setFormData] = useState({ username: '', email: '', password: '', group: 'Read_Only' });
  const [formError, setFormError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [pendingConfirm, setPendingConfirm] = useState(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${API_BASE}/users`, { credentials: 'include' });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Failed to fetch users');
      }
      const data = await res.json();
      setUsers(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Auto-dismiss success toast
  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(''), 2000);
      return () => clearTimeout(timer);
    }
  }, [successMessage]);

  const handleAddClick = () => {
    setEditingUser(null);
    setFormData({ username: '', email: '', password: '', group: 'Read_Only' });
    setFormError('');
    setShowForm(true);
  };

  const handleEditClick = (user) => {
    setEditingUser(user);
    setFormData(buildEditFormData(user));
    setFormError('');
    setShowForm(true);
  };

  const handleCancelForm = () => {
    setShowForm(false);
    setEditingUser(null);
    setFormError('');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setFormError('');

    const url = editingUser
      ? `${API_BASE}/users/${editingUser.id}`
      : `${API_BASE}/users`;
    const method = editingUser ? 'PATCH' : 'POST';

    const body = { ...formData };
    if (editingUser && !body.password) {
      delete body.password;
    }

    try {
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(body),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Operation failed');

      setSuccessMessage(editingUser ? 'User updated successfully' : 'User created successfully');
      setShowForm(false);
      setEditingUser(null);
      fetchUsers();
    } catch (err) {
      setFormError(err.message);
    }
  };

  const handleDelete = async (userId) => {
    setPendingConfirm({
      title: 'Delete User',
      message: 'Are you sure you want to delete this user?',
      confirmText: 'Delete',
      onConfirm: async () => {
        setPendingConfirm(null);
        try {
          const res = await fetch(`${API_BASE}/users/${userId}`, {
            method: 'DELETE',
            credentials: 'include',
          });
          const data = await res.json();
          if (!res.ok) throw new Error(data.error || 'Delete failed');
          setSuccessMessage('User deleted');
          fetchUsers();
        } catch (err) {
          alert(err.message);
        }
      },
    });
  };

  const handleToggleActive = async (user) => {
    try {
      const res = await fetch(`${API_BASE}/users/${user.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ is_active: !user.is_active }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Update failed');
      // Update locally without full reload
      setUsers(prev => prev.map(u => u.id === user.id ? { ...u, is_active: !u.is_active } : u));
    } catch (err) {
      alert(err.message);
    }
  };

  return (
    <div>
      {/* Success toast */}
      {successMessage && (
        <div style={{
          position: 'fixed', bottom: '1.5rem', right: '1.5rem', zIndex: 70,
          background: 'linear-gradient(135deg, rgba(30,41,59,0.98) 0%, rgba(15,23,42,0.99) 100%)',
          border: '1px solid rgba(16,185,129,0.4)',
          borderRadius: '0.5rem',
          boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
          padding: '0.875rem 1.25rem',
          maxWidth: '360px',
          fontFamily: 'monospace', fontSize: '0.75rem',
          color: '#6EE7B7',
          display: 'flex', alignItems: 'center', gap: '0.5rem',
        }}>
          <CheckCircle style={{ width: '14px', height: '14px', color: '#10B981', flexShrink: 0 }} />
          {successMessage}
        </div>
      )}

      {/* Toolbar: Add User button */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
        <div style={{ fontSize: '0.65rem', color: '#334155', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.1em' }}>
          {!loading && !error && `${users.length} user${users.length !== 1 ? 's' : ''}`}
        </div>
        {!showForm && (
          <button
            onClick={handleAddClick}
            className="intel-button intel-button-primary"
            style={{
              display: 'flex', alignItems: 'center', gap: '0.4rem',
              padding: '0.5rem 1rem',
              fontSize: '0.75rem',
            }}
          >
            <Plus style={{ width: '14px', height: '14px' }} />
            Add User
          </button>
        )}
      </div>

      {/* Inline add/edit form */}
      {showForm && (
        <div style={{
          background: 'linear-gradient(135deg, rgba(15,23,42,0.95) 0%, rgba(30,41,59,0.9) 100%)',
          border: '1px solid rgba(14,165,233,0.25)',
          borderRadius: '0.5rem',
          padding: '1.25rem',
          marginBottom: '1rem',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
            <span style={{ fontFamily: 'monospace', fontSize: '0.85rem', fontWeight: '600', color: '#E2E8F0', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
              {editingUser ? 'Edit User' : 'Add New User'}
            </span>
            <button onClick={handleCancelForm} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#64748B', padding: '0.25rem' }}>
              <X style={{ width: '16px', height: '16px' }} />
            </button>
          </div>

          {formError && (
            <div style={{
              display: 'flex', alignItems: 'center', gap: '0.5rem',
              padding: '0.625rem 0.75rem', marginBottom: '0.75rem',
              background: 'rgba(239,68,68,0.08)',
              border: '1px solid rgba(239,68,68,0.3)',
              borderRadius: '0.375rem',
              fontSize: '0.75rem', fontFamily: 'monospace', color: '#FCA5A5',
            }}>
              <AlertCircle style={{ width: '14px', height: '14px', color: '#EF4444', flexShrink: 0 }} />
              {formError}
            </div>
          )}

          <form onSubmit={handleSubmit}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '1rem' }}>
              {/* Username */}
              <div>
                <label style={{ display: 'block', fontSize: '0.65rem', color: '#94A3B8', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.35rem' }}>
                  Username *
                </label>
                <input
                  type="text"
                  required
                  value={formData.username}
                  onChange={e => setFormData({ ...formData, username: e.target.value })}
                  className="intel-input"
                  style={{ width: '100%', boxSizing: 'border-box', fontSize: '0.8rem', padding: '0.5rem 0.75rem' }}
                />
              </div>

              {/* Email */}
              <div>
                <label style={{ display: 'block', fontSize: '0.65rem', color: '#94A3B8', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.35rem' }}>
                  Email *
                </label>
                <input
                  type="email"
                  required
                  value={formData.email}
                  onChange={e => setFormData({ ...formData, email: e.target.value })}
                  className="intel-input"
                  style={{ width: '100%', boxSizing: 'border-box', fontSize: '0.8rem', padding: '0.5rem 0.75rem' }}
                />
              </div>

              {/* Password */}
              <div>
                <label style={{ display: 'block', fontSize: '0.65rem', color: '#94A3B8', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.35rem' }}>
                  Password {editingUser ? '(blank = keep current)' : '*'}
                </label>
                <input
                  type="password"
                  required={!editingUser}
                  value={formData.password}
                  onChange={e => setFormData({ ...formData, password: e.target.value })}
                  className="intel-input"
                  style={{ width: '100%', boxSizing: 'border-box', fontSize: '0.8rem', padding: '0.5rem 0.75rem' }}
                />
              </div>

              {/* Group */}
              <div>
                <label style={{ display: 'block', fontSize: '0.65rem', color: '#94A3B8', fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.35rem' }}>
                  Group *
                </label>
                <select
                  value={formData.group}
                  onChange={e => setFormData({ ...formData, group: e.target.value })}
                  className="intel-input"
                  style={{ width: '100%', boxSizing: 'border-box', fontSize: '0.8rem', padding: '0.5rem 0.75rem', cursor: 'pointer' }}
                >
                  {VALID_GROUPS.map(g => (
                    <option key={g} value={g}>{GROUP_LABELS[g]}</option>
                  ))}
                </select>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '0.5rem' }}>
              <button
                type="submit"
                className="intel-button intel-button-primary"
                style={{ padding: '0.5rem 1.25rem', fontSize: '0.75rem' }}
              >
                {editingUser ? 'Update User' : 'Create User'}
              </button>
              <button
                type="button"
                onClick={handleCancelForm}
                style={{
                  padding: '0.5rem 1.25rem', fontSize: '0.75rem',
                  fontFamily: "'JetBrains Mono', monospace", fontWeight: '600',
                  textTransform: 'uppercase', letterSpacing: '0.5px',
                  background: 'transparent',
                  border: '1px solid rgba(100,116,139,0.4)',
                  borderRadius: '0.375rem',
                  color: '#94A3B8', cursor: 'pointer',
                }}
              >
                Cancel
              </button>
            </div>
          </form>
        </div>
      )}

      {/* Loading state */}
      {loading && (
        <div style={{ padding: '3rem', textAlign: 'center' }}>
          <Loader className="loading-spinner" style={{ width: '28px', height: '28px', color: '#0EA5E9', margin: '0 auto' }} />
          <div style={{ marginTop: '0.75rem', fontSize: '0.75rem', color: '#64748B', fontFamily: 'monospace' }}>Loading users...</div>
        </div>
      )}

      {/* Error banner */}
      {!loading && error && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: '0.5rem',
          padding: '0.875rem 1rem',
          background: 'rgba(239,68,68,0.08)',
          border: '1px solid rgba(239,68,68,0.3)',
          borderRadius: '0.375rem',
          fontSize: '0.8rem', fontFamily: 'monospace', color: '#FCA5A5',
        }}>
          <AlertCircle style={{ width: '16px', height: '16px', color: '#EF4444', flexShrink: 0 }} />
          {error}
        </div>
      )}

      {/* User table */}
      {!loading && !error && (
        <div style={{
          background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
          border: '1px solid rgba(14,165,233,0.15)',
          borderRadius: '0.5rem',
          overflow: 'hidden',
        }}>
          {/* Column headers */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1.5fr 2fr 1fr 1fr 1.5fr 0.8fr',
            padding: '0.625rem 1rem',
            borderBottom: '1px solid rgba(255,255,255,0.05)',
            fontSize: '0.62rem', color: '#334155',
            fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.08em',
          }}>
            <span>Username</span>
            <span>Email</span>
            <span>Group</span>
            <span>Active</span>
            <span>Last Login</span>
            <span style={{ textAlign: 'right' }}>Actions</span>
          </div>

          {/* Rows */}
          {users.length === 0 ? (
            <div style={{ padding: '2rem', textAlign: 'center', color: '#334155', fontFamily: 'monospace', fontSize: '0.8rem' }}>
              No users found
            </div>
          ) : (
            users.map(u => {
              const badge = getGroupBadgeStyle(u.group);
              const self = isSelfUser(currentUser?.id, u.id);
              return (
                <div
                  key={u.id}
                  className="data-row"
                  style={{
                    display: 'grid',
                    gridTemplateColumns: '1.5fr 2fr 1fr 1fr 1.5fr 0.8fr',
                    padding: '0.625rem 1rem',
                    alignItems: 'center',
                    fontSize: '0.8rem',
                    transition: 'background 0.15s',
                  }}
                >
                  {/* Username */}
                  <span style={{ color: '#F8FAFC', fontWeight: '600', fontFamily: 'monospace' }}>
                    {u.username}
                  </span>

                  {/* Email */}
                  <span style={{ color: '#E2E8F0', fontFamily: 'monospace', fontSize: '0.75rem' }}>
                    {u.email}
                  </span>

                  {/* Group badge */}
                  <span>
                    <span style={{
                      display: 'inline-block',
                      padding: '0.15rem 0.5rem',
                      borderRadius: '0.25rem',
                      fontSize: '0.65rem',
                      fontFamily: 'monospace',
                      fontWeight: '600',
                      background: badge.bg,
                      border: `1px solid ${badge.border}`,
                      color: badge.text,
                    }}>
                      {u.group ? u.group.replace('_', ' ') : 'Read Only'}
                    </span>
                  </span>

                  {/* Active toggle */}
                  <span>
                    <button
                      onClick={() => !self && handleToggleActive(u)}
                      disabled={self}
                      style={{
                        padding: '0.15rem 0.5rem',
                        borderRadius: '0.25rem',
                        fontSize: '0.65rem',
                        fontFamily: 'monospace',
                        fontWeight: '600',
                        cursor: self ? 'not-allowed' : 'pointer',
                        opacity: self ? 0.5 : 1,
                        background: u.is_active ? 'rgba(16,185,129,0.15)' : 'rgba(239,68,68,0.15)',
                        border: `1px solid ${u.is_active ? '#10B981' : '#EF4444'}`,
                        color: u.is_active ? '#6EE7B7' : '#FCA5A5',
                        transition: 'all 0.15s',
                      }}
                      title={self ? 'Cannot toggle your own account' : (u.is_active ? 'Deactivate' : 'Activate')}
                    >
                      {u.is_active ? 'Active' : 'Inactive'}
                    </button>
                  </span>

                  {/* Last login */}
                  <span style={{ color: '#94A3B8', fontFamily: 'monospace', fontSize: '0.72rem' }}>
                    {u.last_login
                      ? new Date(u.last_login).toLocaleString()
                      : 'Never'}
                  </span>

                  {/* Actions */}
                  <span style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.25rem' }}>
                    <button
                      onClick={() => handleEditClick(u)}
                      title="Edit user"
                      style={{
                        background: 'none', border: '1px solid rgba(14,165,233,0.2)',
                        borderRadius: '0.25rem', padding: '0.3rem',
                        cursor: 'pointer', color: '#64748B',
                        transition: 'all 0.15s',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.color = '#0EA5E9'; e.currentTarget.style.borderColor = 'rgba(14,165,233,0.5)'; }}
                      onMouseLeave={e => { e.currentTarget.style.color = '#64748B'; e.currentTarget.style.borderColor = 'rgba(14,165,233,0.2)'; }}
                    >
                      <Edit2 style={{ width: '13px', height: '13px' }} />
                    </button>
                    <button
                      onClick={() => !self && handleDelete(u.id)}
                      disabled={self}
                      title={self ? 'Cannot delete your own account' : 'Delete user'}
                      style={{
                        background: 'none', border: '1px solid rgba(239,68,68,0.2)',
                        borderRadius: '0.25rem', padding: '0.3rem',
                        cursor: self ? 'not-allowed' : 'pointer',
                        color: self ? '#334155' : '#64748B',
                        opacity: self ? 0.4 : 1,
                        transition: 'all 0.15s',
                      }}
                      onMouseEnter={e => { if (!self) { e.currentTarget.style.color = '#EF4444'; e.currentTarget.style.borderColor = 'rgba(239,68,68,0.5)'; } }}
                      onMouseLeave={e => { if (!self) { e.currentTarget.style.color = '#64748B'; e.currentTarget.style.borderColor = 'rgba(239,68,68,0.2)'; } }}
                    >
                      <Trash2 style={{ width: '13px', height: '13px' }} />
                    </button>
                  </span>
                </div>
              );
            })
          )}
        </div>
      )}

      {/* Confirmation Modal */}
      <ConfirmModal
        open={!!pendingConfirm}
        title={pendingConfirm?.title}
        message={pendingConfirm?.message}
        confirmText={pendingConfirm?.confirmText}
        variant="danger"
        onConfirm={pendingConfirm?.onConfirm}
        onCancel={() => setPendingConfirm(null)}
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// AuditLogPanel
// ---------------------------------------------------------------------------
const ENTITY_TYPES = ['auth', 'cve', 'document', 'user'];

function AuditLogPanel() {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [pagination, setPagination] = useState({ page: 1, limit: 25, total: 0, totalPages: 0 });
  const [actions, setActions] = useState([]);

  // Filter state
  const [userFilter, setUserFilter] = useState('');
  const [actionFilter, setActionFilter] = useState('');
  const [entityTypeFilter, setEntityTypeFilter] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  const fetchLogs = useCallback(async (page = 1) => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ page, limit: 25 });
      if (userFilter) params.append('user', userFilter);
      if (actionFilter) params.append('action', actionFilter);
      if (entityTypeFilter) params.append('entityType', entityTypeFilter);
      if (startDate) params.append('startDate', startDate);
      if (endDate) params.append('endDate', endDate);

      const res = await fetch(`${API_BASE}/audit-logs?${params}`, { credentials: 'include' });
      if (!res.ok) throw new Error('Failed to fetch audit logs');
      const data = await res.json();
      setLogs(data.logs);
      setPagination(data.pagination);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [userFilter, actionFilter, entityTypeFilter, startDate, endDate]);

  const fetchActions = useCallback(async () => {
    try {
      const res = await fetch(`${API_BASE}/audit-logs/actions`, { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setActions(data);
      }
    } catch {
      // Non-critical — silently ignored
    }
  }, []);

  useEffect(() => {
    fetchLogs(1);
    fetchActions();
  }, [fetchLogs, fetchActions]);

  const formatDate = (dateStr) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString();
  };

  const formatDetails = (details) => {
    if (!details) return '-';
    try {
      const parsed = typeof details === 'string' ? JSON.parse(details) : details;
      return Object.entries(parsed)
        .map(([k, v]) => `${k}: ${v}`)
        .join(', ');
    } catch {
      return details;
    }
  };

  const handleApplyFilters = (e) => {
    e.preventDefault();
    fetchLogs(1);
  };

  const handleClearFilters = () => {
    setUserFilter('');
    setActionFilter('');
    setEntityTypeFilter('');
    setStartDate('');
    setEndDate('');
  };

  const labelStyle = {
    display: 'block',
    fontSize: '0.62rem',
    color: '#64748B',
    fontFamily: 'monospace',
    textTransform: 'uppercase',
    letterSpacing: '0.05em',
    marginBottom: '0.3rem',
  };

  const filterInputStyle = {
    width: '100%',
    boxSizing: 'border-box',
    fontSize: '0.78rem',
    padding: '0.45rem 0.65rem',
  };

  return (
    <div>
      {/* ── Filter bar ──────────────────────────────────────────── */}
      <form onSubmit={handleApplyFilters} style={{ marginBottom: '1rem' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(5, 1fr)',
          gap: '0.65rem',
          marginBottom: '0.75rem',
        }}>
          {/* Username */}
          <div>
            <label style={labelStyle}>Username</label>
            <div style={{ position: 'relative' }}>
              <Search style={{
                position: 'absolute', left: '0.5rem', top: '50%', transform: 'translateY(-50%)',
                width: '13px', height: '13px', color: '#475569', pointerEvents: 'none',
              }} />
              <input
                type="text"
                placeholder="Search user..."
                value={userFilter}
                onChange={e => setUserFilter(e.target.value)}
                className="intel-input"
                style={{ ...filterInputStyle, paddingLeft: '1.75rem' }}
              />
            </div>
          </div>

          {/* Action type */}
          <div>
            <label style={labelStyle}>Action</label>
            <select
              value={actionFilter}
              onChange={e => setActionFilter(e.target.value)}
              className="intel-input"
              style={{ ...filterInputStyle, cursor: 'pointer' }}
            >
              <option value="">All Actions</option>
              {actions.map(a => (
                <option key={a} value={a}>{a}</option>
              ))}
            </select>
          </div>

          {/* Entity type */}
          <div>
            <label style={labelStyle}>Entity Type</label>
            <select
              value={entityTypeFilter}
              onChange={e => setEntityTypeFilter(e.target.value)}
              className="intel-input"
              style={{ ...filterInputStyle, cursor: 'pointer' }}
            >
              <option value="">All Types</option>
              {ENTITY_TYPES.map(t => (
                <option key={t} value={t}>{t}</option>
              ))}
            </select>
          </div>

          {/* Start date */}
          <div>
            <label style={labelStyle}>Start Date</label>
            <input
              type="date"
              value={startDate}
              onChange={e => setStartDate(e.target.value)}
              className="intel-input"
              style={filterInputStyle}
            />
          </div>

          {/* End date */}
          <div>
            <label style={labelStyle}>End Date</label>
            <input
              type="date"
              value={endDate}
              onChange={e => setEndDate(e.target.value)}
              className="intel-input"
              style={filterInputStyle}
            />
          </div>
        </div>

        <div style={{ display: 'flex', gap: '0.5rem' }}>
          <button
            type="submit"
            className="intel-button intel-button-primary"
            style={{ padding: '0.45rem 1rem', fontSize: '0.72rem' }}
          >
            Apply Filters
          </button>
          <button
            type="button"
            onClick={handleClearFilters}
            style={{
              padding: '0.45rem 1rem', fontSize: '0.72rem',
              fontFamily: "'JetBrains Mono', monospace", fontWeight: '600',
              textTransform: 'uppercase', letterSpacing: '0.5px',
              background: 'transparent',
              border: '1px solid rgba(100,116,139,0.4)',
              borderRadius: '0.375rem',
              color: '#94A3B8', cursor: 'pointer',
            }}
          >
            Clear
          </button>
        </div>
      </form>

      {/* ── Loading state ───────────────────────────────────────── */}
      {loading && (
        <div style={{ padding: '3rem', textAlign: 'center' }}>
          <Loader className="loading-spinner" style={{ width: '28px', height: '28px', color: '#0EA5E9', margin: '0 auto' }} />
          <div style={{ marginTop: '0.75rem', fontSize: '0.75rem', color: '#64748B', fontFamily: 'monospace' }}>Loading audit logs...</div>
        </div>
      )}

      {/* ── Error banner ────────────────────────────────────────── */}
      {!loading && error && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: '0.5rem',
          padding: '0.875rem 1rem',
          background: 'rgba(239,68,68,0.08)',
          border: '1px solid rgba(239,68,68,0.3)',
          borderRadius: '0.375rem',
          fontSize: '0.8rem', fontFamily: 'monospace', color: '#FCA5A5',
        }}>
          <AlertCircle style={{ width: '16px', height: '16px', color: '#EF4444', flexShrink: 0 }} />
          {error}
        </div>
      )}

      {/* ── Empty state ─────────────────────────────────────────── */}
      {!loading && !error && logs.length === 0 && (
        <div style={{
          padding: '3rem', textAlign: 'center',
          color: '#94A3B8', fontFamily: 'monospace', fontSize: '0.85rem',
        }}>
          No audit log entries found
        </div>
      )}

      {/* ── Log table ───────────────────────────────────────────── */}
      {!loading && !error && logs.length > 0 && (
        <div style={{
          background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
          border: '1px solid rgba(14,165,233,0.15)',
          borderRadius: '0.5rem',
          overflow: 'hidden',
        }}>
          {/* Column headers */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '1.4fr 1fr 1.1fr 0.9fr 0.8fr 1.6fr 1fr',
            padding: '0.625rem 1rem',
            borderBottom: '1px solid rgba(255,255,255,0.05)',
            fontSize: '0.62rem', color: '#334155',
            fontFamily: 'monospace', textTransform: 'uppercase', letterSpacing: '0.08em',
          }}>
            <span>Timestamp</span>
            <span>Username</span>
            <span>Action</span>
            <span>Entity Type</span>
            <span>Entity ID</span>
            <span>Details</span>
            <span>IP Address</span>
          </div>

          {/* Rows */}
          {logs.map(log => {
            const badge = getActionBadgeStyle(log.action);
            return (
              <div
                key={log.id}
                className="data-row"
                style={{
                  display: 'grid',
                  gridTemplateColumns: '1.4fr 1fr 1.1fr 0.9fr 0.8fr 1.6fr 1fr',
                  padding: '0.55rem 1rem',
                  alignItems: 'center',
                  fontSize: '0.78rem',
                  transition: 'background 0.15s',
                }}
              >
                {/* Timestamp — monospace */}
                <span style={{ color: '#CBD5E1', fontFamily: "'JetBrains Mono', monospace", fontSize: '0.72rem' }}>
                  {formatDate(log.created_at)}
                </span>

                {/* Username */}
                <span style={{ color: '#F8FAFC', fontWeight: '600', fontFamily: 'monospace' }}>
                  {log.username}
                </span>

                {/* Action badge */}
                <span>
                  <span style={{
                    display: 'inline-block',
                    padding: '0.15rem 0.5rem',
                    borderRadius: '0.25rem',
                    fontSize: '0.65rem',
                    fontFamily: 'monospace',
                    fontWeight: '600',
                    background: badge.bg,
                    border: `1px solid ${badge.border}`,
                    color: badge.text,
                  }}>
                    {log.action}
                  </span>
                </span>

                {/* Entity type */}
                <span style={{ color: '#94A3B8', fontFamily: 'monospace', fontSize: '0.75rem' }}>
                  {log.entity_type || '-'}
                </span>

                {/* Entity ID */}
                <span style={{ color: '#CBD5E1', fontFamily: 'monospace', fontSize: '0.72rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {log.entity_id || '-'}
                </span>

                {/* Details */}
                <span
                  style={{ color: '#94A3B8', fontFamily: 'monospace', fontSize: '0.7rem', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                  title={formatDetails(log.details)}
                >
                  {formatDetails(log.details)}
                </span>

                {/* IP address — monospace */}
                <span style={{ color: '#CBD5E1', fontFamily: "'JetBrains Mono', monospace", fontSize: '0.72rem' }}>
                  {log.ip_address || '-'}
                </span>
              </div>
            );
          })}
        </div>
      )}

      {/* ── Pagination ──────────────────────────────────────────── */}
      {!loading && !error && pagination.totalPages > 0 && (
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          marginTop: '0.75rem',
          padding: '0.5rem 0',
        }}>
          <span style={{ fontSize: '0.72rem', color: '#64748B', fontFamily: 'monospace' }}>
            {pagination.total} {pagination.total === 1 ? 'entry' : 'entries'} — Page {pagination.page} of {pagination.totalPages}
          </span>
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.375rem' }}>
            <button
              onClick={() => fetchLogs(pagination.page - 1)}
              disabled={pagination.page <= 1}
              className="intel-button intel-button-primary"
              style={{
                padding: '0.35rem 0.6rem', fontSize: '0.72rem',
                opacity: pagination.page <= 1 ? 0.4 : 1,
                cursor: pagination.page <= 1 ? 'not-allowed' : 'pointer',
                display: 'flex', alignItems: 'center', gap: '0.25rem',
              }}
            >
              <ChevronLeft style={{ width: '14px', height: '14px' }} />
              Previous
            </button>
            <span style={{ fontSize: '0.75rem', color: '#CBD5E1', fontFamily: 'monospace', padding: '0 0.5rem' }}>
              {pagination.page}
            </span>
            <button
              onClick={() => fetchLogs(pagination.page + 1)}
              disabled={pagination.page >= pagination.totalPages}
              className="intel-button intel-button-primary"
              style={{
                padding: '0.35rem 0.6rem', fontSize: '0.72rem',
                opacity: pagination.page >= pagination.totalPages ? 0.4 : 1,
                cursor: pagination.page >= pagination.totalPages ? 'not-allowed' : 'pointer',
                display: 'flex', alignItems: 'center', gap: '0.25rem',
              }}
            >
              Next
              <ChevronRight style={{ width: '14px', height: '14px' }} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// SystemInfoPanel
// ---------------------------------------------------------------------------
function SystemInfoPanel() {
  const [users, setUsers] = useState([]);
  const [recentLogs, setRecentLogs] = useState([]);
  const [totalAuditEntries, setTotalAuditEntries] = useState(0);
  const [loading, setLoading] = useState(true);
  const [errors, setErrors] = useState({ users: null, logs: null });

  useEffect(() => {
    let mounted = true;

    async function fetchData() {
      setLoading(true);
      const newErrors = { users: null, logs: null };

      // Fetch users and audit logs in parallel
      const [usersResult, logsResult] = await Promise.allSettled([
        fetch(`${API_BASE}/users`, { credentials: 'include' }).then(res => {
          if (!res.ok) throw new Error('Failed to fetch users');
          return res.json();
        }),
        fetch(`${API_BASE}/audit-logs?limit=10&page=1`, { credentials: 'include' }).then(res => {
          if (!res.ok) throw new Error('Failed to fetch audit logs');
          return res.json();
        }),
      ]);

      if (!mounted) return;

      if (usersResult.status === 'fulfilled') {
        setUsers(usersResult.value);
      } else {
        newErrors.users = usersResult.reason?.message || 'Failed to fetch users';
      }

      if (logsResult.status === 'fulfilled') {
        setRecentLogs(logsResult.value.logs || []);
        setTotalAuditEntries(logsResult.value.pagination?.total || 0);
      } else {
        newErrors.logs = logsResult.reason?.message || 'Failed to fetch audit logs';
      }

      setErrors(newErrors);
      setLoading(false);
    }

    fetchData();
    return () => { mounted = false; };
  }, []);

  // Derived stats
  const totalUsers = users.length;
  const activeUsers = users.filter(u => u.is_active).length;
  const recentLogins = computeRecentLogins(users);

  const statCards = [
    {
      label: 'Total Users',
      value: errors.users ? null : totalUsers,
      icon: Users,
      accentColor: '#0EA5E9',
      accentBg: 'rgba(14,165,233,0.15)',
      accentBorder: 'rgba(14,165,233,0.35)',
      error: errors.users,
    },
    {
      label: 'Active Users',
      value: errors.users ? null : activeUsers,
      icon: Shield,
      accentColor: '#10B981',
      accentBg: 'rgba(16,185,129,0.15)',
      accentBorder: 'rgba(16,185,129,0.35)',
      error: errors.users,
    },
    {
      label: 'Recent Logins (7d)',
      value: errors.users ? null : recentLogins,
      icon: Clock,
      accentColor: '#F59E0B',
      accentBg: 'rgba(245,158,11,0.15)',
      accentBorder: 'rgba(245,158,11,0.35)',
      error: errors.users,
    },
    {
      label: 'Audit Entries',
      value: errors.logs ? null : totalAuditEntries,
      icon: FileText,
      accentColor: '#8B5CF6',
      accentBg: 'rgba(139,92,246,0.15)',
      accentBorder: 'rgba(139,92,246,0.35)',
      error: errors.logs,
    },
  ];

  if (loading) {
    return (
      <div style={{ padding: '3rem', textAlign: 'center' }}>
        <Loader className="loading-spinner" style={{ width: '28px', height: '28px', color: '#0EA5E9', margin: '0 auto' }} />
        <div style={{ marginTop: '0.75rem', fontSize: '0.75rem', color: '#64748B', fontFamily: 'monospace' }}>Loading system info...</div>
      </div>
    );
  }

  return (
    <div>
      {/* ── Stat cards ──────────────────────────────────────────── */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(4, 1fr)',
        gap: '1rem',
        marginBottom: '1.5rem',
      }}>
        {statCards.map(card => {
          const CardIcon = card.icon;
          return (
            <div
              key={card.label}
              className="stat-card"
              style={{
                borderColor: card.accentBorder,
                position: 'relative',
                overflow: 'hidden',
              }}
            >
              {/* Accent top bar */}
              <div style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                height: '2px',
                background: `linear-gradient(90deg, transparent, ${card.accentColor}, transparent)`,
                opacity: 0.8,
                boxShadow: `0 0 8px ${card.accentColor}`,
              }} />

              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                <div>
                  {card.error ? (
                    <div style={{
                      fontSize: '0.8rem',
                      fontFamily: 'monospace',
                      color: '#FCA5A5',
                      marginBottom: '0.25rem',
                    }}>
                      Unable to load
                    </div>
                  ) : (
                    <div style={{
                      fontSize: '1.75rem',
                      fontWeight: '700',
                      fontFamily: "'JetBrains Mono', monospace",
                      color: '#F8FAFC',
                      lineHeight: 1,
                      marginBottom: '0.35rem',
                    }}>
                      {card.value}
                    </div>
                  )}
                  <div style={{
                    fontSize: '0.65rem',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: '0.08em',
                    color: '#94A3B8',
                  }}>
                    {card.label}
                  </div>
                </div>
                <div style={{
                  padding: '0.5rem',
                  borderRadius: '0.375rem',
                  background: card.accentBg,
                  border: `1px solid ${card.accentBorder}`,
                }}>
                  <CardIcon style={{ width: '18px', height: '18px', color: card.accentColor }} />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* ── Recent Activity ─────────────────────────────────────── */}
      <div>
        <h3 style={{
          fontFamily: 'monospace',
          fontSize: '0.85rem',
          fontWeight: '600',
          color: '#E2E8F0',
          textTransform: 'uppercase',
          letterSpacing: '0.06em',
          marginBottom: '0.75rem',
        }}>
          Recent Activity
        </h3>

        {errors.logs ? (
          <div style={{
            display: 'flex', alignItems: 'center', gap: '0.5rem',
            padding: '0.875rem 1rem',
            background: 'rgba(239,68,68,0.08)',
            border: '1px solid rgba(239,68,68,0.3)',
            borderRadius: '0.375rem',
            fontSize: '0.8rem', fontFamily: 'monospace', color: '#FCA5A5',
          }}>
            <AlertCircle style={{ width: '16px', height: '16px', color: '#EF4444', flexShrink: 0 }} />
            Unable to load recent activity
          </div>
        ) : recentLogs.length === 0 ? (
          <div style={{
            padding: '2rem', textAlign: 'center',
            color: '#94A3B8', fontFamily: 'monospace', fontSize: '0.85rem',
          }}>
            No recent activity
          </div>
        ) : (
          <div style={{
            background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
            border: '1px solid rgba(14,165,233,0.15)',
            borderRadius: '0.5rem',
            overflow: 'hidden',
          }}>
            {recentLogs.map((log, idx) => {
              const badge = getActionBadgeStyle(log.action);
              return (
                <div
                  key={log.id || idx}
                  className="data-row"
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.75rem',
                    padding: '0.5rem 1rem',
                    fontSize: '0.78rem',
                    transition: 'background 0.15s',
                  }}
                >
                  {/* Timestamp */}
                  <span style={{
                    color: '#64748B',
                    fontFamily: "'JetBrains Mono', monospace",
                    fontSize: '0.7rem',
                    minWidth: '140px',
                    flexShrink: 0,
                  }}>
                    {log.created_at ? new Date(log.created_at).toLocaleString() : '-'}
                  </span>

                  {/* Username */}
                  <span style={{
                    color: '#F8FAFC',
                    fontWeight: '600',
                    fontFamily: 'monospace',
                    fontSize: '0.75rem',
                    minWidth: '90px',
                    flexShrink: 0,
                  }}>
                    {log.username}
                  </span>

                  {/* Action badge */}
                  <span style={{
                    display: 'inline-block',
                    padding: '0.1rem 0.45rem',
                    borderRadius: '0.25rem',
                    fontSize: '0.62rem',
                    fontFamily: 'monospace',
                    fontWeight: '600',
                    background: badge.bg,
                    border: `1px solid ${badge.border}`,
                    color: badge.text,
                    flexShrink: 0,
                  }}>
                    {log.action}
                  </span>

                  {/* Entity info */}
                  <span style={{
                    color: '#94A3B8',
                    fontFamily: 'monospace',
                    fontSize: '0.72rem',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    flex: 1,
                  }}>
                    {log.entity_type}{log.entity_id ? ` #${log.entity_id}` : ''}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// AdminPage
// ---------------------------------------------------------------------------
export default function AdminPage() {
  const [activeTab, setActiveTab] = useState('users');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem', paddingBottom: '2rem' }}>

      {/* ── Page header ─────────────────────────────────────────── */}
      <div>
        <h2 style={{
          fontFamily: 'monospace',
          fontSize: '1.5rem',
          fontWeight: '700',
          color: '#0EA5E9',
          textTransform: 'uppercase',
          letterSpacing: '0.1em',
          textShadow: '0 0 16px rgba(14, 165, 233, 0.4), 0 0 32px rgba(14, 165, 233, 0.15)',
          marginBottom: '0.25rem',
        }}>
          Admin Panel
        </h2>
        <div style={{
          fontSize: '0.72rem',
          color: '#475569',
          fontFamily: 'monospace',
        }}>
          User management, audit logs &amp; system information
        </div>
      </div>

      {/* ── Tab navigation ──────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: '0.375rem' }}>
        {TABS.map(({ id, label, icon: Icon }) => {
          const isActive = activeTab === id;
          return (
            <button
              key={id}
              onClick={() => setActiveTab(id)}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '0.5rem',
                padding: '0.5rem 1.25rem',
                cursor: 'pointer',
                fontFamily: 'monospace',
                fontSize: '0.8rem',
                fontWeight: '600',
                textTransform: 'uppercase',
                letterSpacing: '0.06em',
                borderRadius: '0.375rem',
                border: isActive
                  ? '1px solid #0EA5E9'
                  : '1px solid rgba(14, 165, 233, 0.2)',
                background: isActive
                  ? 'rgba(14, 165, 233, 0.1)'
                  : 'transparent',
                color: isActive ? '#0EA5E9' : '#475569',
                transition: 'all 0.15s',
              }}
              onMouseEnter={e => {
                if (!isActive) {
                  e.currentTarget.style.color = '#94A3B8';
                  e.currentTarget.style.borderColor = 'rgba(14, 165, 233, 0.4)';
                }
              }}
              onMouseLeave={e => {
                if (!isActive) {
                  e.currentTarget.style.color = '#475569';
                  e.currentTarget.style.borderColor = 'rgba(14, 165, 233, 0.2)';
                }
              }}
            >
              <Icon style={{ width: '14px', height: '14px' }} />
              {label}
            </button>
          );
        })}
      </div>

      {/* ── Panel content ───────────────────────────────────────── */}
      {activeTab === 'users' && (
        <div
          className="intel-card"
          style={{ borderRadius: '0.5rem', padding: '1.25rem' }}
        >
          <UserManagementPanel />
        </div>
      )}

      {activeTab === 'audit' && (
        <div
          className="intel-card"
          style={{ borderRadius: '0.5rem', padding: '1.25rem' }}
        >
          <AuditLogPanel />
        </div>
      )}

      {activeTab === 'system' && (
        <div
          className="intel-card"
          style={{ borderRadius: '0.5rem', padding: '1.25rem' }}
        >
          <SystemInfoPanel />
        </div>
      )}
    </div>
  );
}
