/* ============================================================
   MaintenanceOS — Admin Dashboard
   User management, system stats, and admin controls
   ============================================================ */

const { UserIcon, SettingsIcon, ActivityIcon, AlertTriangleIcon, CheckCircleIcon,
        XCircleIcon, PlusIcon, EditIcon, TrashIcon, ShieldIcon } = Icons;

function AdminDashboard() {
  const { ADMIN_STATS, USER_ACTIVITY, SYSTEM_NOTIFICATIONS } = window.ADMIN_DATA;
  const [activeTab, setActiveTab] = useState("overview");

  return (
    <div className="screen">
      <div className="screen-header">
        <h1>Admin Dashboard</h1>
        <p>System management, user administration, and platform controls</p>
      </div>

      {/* Admin Navigation Tabs */}
      <div style={{
        display: "flex", gap: "1px", marginBottom: 32,
        background: "var(--surface-2)", borderRadius: "var(--radius-md)",
        padding: 4
      }}>
        {[
          { id: "overview", label: "Overview", icon: "dashboard" },
          { id: "users", label: "User Management", icon: "users" },
          { id: "activity", label: "Activity Log", icon: "activity" },
          { id: "system", label: "System Health", icon: "settings" }
        ].map(tab => (
          <button key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            style={{
              flex: 1, padding: "12px 16px", borderRadius: "var(--radius-sm)",
              background: activeTab === tab.id ? "var(--bg)" : "transparent",
              color: activeTab === tab.id ? "var(--text)" : "var(--text-muted)",
              fontWeight: activeTab === tab.id ? 600 : 500,
              fontSize: 14, display: "flex", alignItems: "center", gap: 8,
              justifyContent: "center", cursor: "pointer", border: "none",
              transition: "all 0.2s ease"
            }}>
            <Icon name={tab.icon} size={16} />
            {tab.label}
          </button>
        ))}
      </div>

      {activeTab === "overview" && <AdminOverview stats={ADMIN_STATS} notifications={SYSTEM_NOTIFICATIONS} />}
      {activeTab === "users" && <UserManagement />}
      {activeTab === "activity" && <ActivityLog activity={USER_ACTIVITY} />}
      {activeTab === "system" && <SystemHealth />}
    </div>
  );
}

function AdminOverview({ stats, notifications }) {
  return (
    <div>
      {/* Key Metrics */}
      <div className="grid-4" style={{ marginBottom: 32 }}>
        <MetricCard
          title="Total Users"
          value={stats.totalUsers}
          change="+3 this month"
          trend="up"
          icon="users"
          color="var(--blue-500)"
        />
        <MetricCard
          title="Active Users"
          value={stats.activeUsers}
          change="98.5% uptime"
          trend="stable"
          icon="userCheck"
          color="var(--green-500)"
        />
        <MetricCard
          title="Open Tickets"
          value={stats.openTickets}
          change="-2 from yesterday"
          trend="down"
          icon="alertCircle"
          color="var(--orange-500)"
        />
        <MetricCard
          title="Avg Response"
          value={stats.avgResponseTime}
          change="15% faster"
          trend="up"
          icon="clock"
          color="var(--purple-500)"
        />
      </div>

      <div className="grid-2">
        {/* System Status */}
        <div className="card">
          <div className="card-header">
            <h3>System Status</h3>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <div style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--green-500)" }} />
              <span style={{ color: "var(--green-500)", fontWeight: 600, fontSize: 14 }}>All Systems Operational</span>
            </div>
          </div>
          <div className="card-content">
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <SystemStatusItem label="Database" status="operational" uptime="99.99%" />
              <SystemStatusItem label="File Storage" status="operational" uptime="99.95%" />
              <SystemStatusItem label="Email Service" status="operational" uptime="100%" />
              <SystemStatusItem label="Mobile API" status="operational" uptime="99.89%" />
              <SystemStatusItem label="Backup System" status="warning" uptime="95.2%" />
            </div>
          </div>
        </div>

        {/* Recent Notifications */}
        <div className="card">
          <div className="card-header">
            <h3>System Notifications</h3>
            <button className="btn btn-sm">View All</button>
          </div>
          <div className="card-content">
            {notifications.slice(0, 4).map(notif => (
              <div key={notif.id} style={{
                display: "flex", gap: 12, padding: "12px 0",
                borderBottom: "1px solid var(--border)"
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  display: "flex", alignItems: "center", justifyContent: "center",
                  background: notif.type === "warning" ? "var(--orange-100)" :
                           notif.type === "success" ? "var(--green-100)" : "var(--blue-100)"
                }}>
                  <Icon name={notif.type === "warning" ? "alertTriangle" :
                              notif.type === "success" ? "checkCircle" : "info"}
                        size={16}
                        color={notif.type === "warning" ? "var(--orange-600)" :
                               notif.type === "success" ? "var(--green-600)" : "var(--blue-600)"} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{notif.title}</div>
                  <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{notif.message}</div>
                  <div style={{ fontSize: 12, color: "var(--text-faint)", marginTop: 4 }}>
                    {new Date(notif.timestamp).toLocaleString()}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function UserManagement() {
  const { USERS, USER_ROLES } = window.ADMIN_DATA;
  const [selectedUser, setSelectedUser] = useState(null);
  const [showCreateUser, setShowCreateUser] = useState(false);

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
        <div>
          <h2 style={{ marginBottom: 4 }}>User Management</h2>
          <p style={{ color: "var(--text-muted)" }}>Manage user accounts, roles, and permissions</p>
        </div>
        <button
          className="btn btn-primary"
          onClick={() => setShowCreateUser(true)}
          style={{ display: "flex", alignItems: "center", gap: 8 }}
        >
          <Icon name="plus" size={16} />
          Add User
        </button>
      </div>

      {/* Role Statistics */}
      <div className="grid-4" style={{ marginBottom: 32 }}>
        {Object.entries(USER_ROLES).map(([roleId, role]) => {
          const userCount = USERS.filter(u => u.role === roleId).length;
          return (
            <div key={roleId} className="card" style={{ textAlign: "center", padding: 20 }}>
              <div style={{
                width: 48, height: 48, borderRadius: 12, margin: "0 auto 12px",
                background: role.color + "20", display: "flex",
                alignItems: "center", justifyContent: "center"
              }}>
                <Icon name="shield" size={24} color={role.color} />
              </div>
              <div style={{ fontWeight: 600, marginBottom: 4 }}>{role.name}</div>
              <div style={{ fontSize: 24, fontWeight: 700, color: role.color, marginBottom: 4 }}>{userCount}</div>
              <div style={{ fontSize: 12, color: "var(--text-muted)" }}>users</div>
            </div>
          );
        })}
      </div>

      {/* Users Table */}
      <div className="card">
        <div className="table-container">
          <table className="data-table">
            <thead>
              <tr>
                <th>User</th>
                <th>Role</th>
                <th>Department</th>
                <th>Last Login</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {USERS.map(user => (
                <UserTableRow
                  key={user.id}
                  user={user}
                  onEdit={() => setSelectedUser(user)}
                />
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* User Detail Modal */}
      {selectedUser && (
        <UserDetailModal
          user={selectedUser}
          onClose={() => setSelectedUser(null)}
        />
      )}

      {/* Create User Modal */}
      {showCreateUser && (
        <CreateUserModal
          onClose={() => setShowCreateUser(false)}
        />
      )}
    </div>
  );
}

function UserTableRow({ user, onEdit }) {
  const { formatLastLogin } = window.ADMIN_HELPERS;
  const role = window.ADMIN_DATA.USER_ROLES[user.role];

  return (
    <tr>
      <td>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div className="avatar" style={{
            width: 32, height: 32, borderRadius: 8,
            background: "var(--surface-3)", display: "flex",
            alignItems: "center", justifyContent: "center",
            fontWeight: 600, fontSize: 12
          }}>
            {user.initials}
          </div>
          <div>
            <div style={{ fontWeight: 600 }}>{user.name}</div>
            <div style={{ fontSize: 13, color: "var(--text-muted)" }}>{user.email}</div>
          </div>
        </div>
      </td>
      <td>
        <span className="badge" style={{
          background: role.color + "20",
          color: role.color,
          fontWeight: 600
        }}>
          {role.name}
        </span>
      </td>
      <td style={{ color: "var(--text-muted)" }}>{user.department}</td>
      <td style={{ color: "var(--text-muted)" }}>{formatLastLogin(user.lastLogin)}</td>
      <td>
        <span className={`badge badge-${user.status}`}>
          {user.status === "active" ? "Active" : "Inactive"}
        </span>
      </td>
      <td>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn-icon" onClick={onEdit}>
            <Icon name="edit" size={14} />
          </button>
          <button className="btn-icon btn-danger">
            <Icon name="trash" size={14} />
          </button>
        </div>
      </td>
    </tr>
  );
}

function SystemStatusItem({ label, status, uptime }) {
  const statusColors = {
    operational: "var(--green-500)",
    warning: "var(--orange-500)",
    error: "var(--red-500)"
  };

  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{
          width: 8, height: 8, borderRadius: "50%",
          background: statusColors[status]
        }} />
        <span style={{ fontWeight: 500 }}>{label}</span>
      </div>
      <span style={{ color: "var(--text-muted)", fontSize: 13 }}>{uptime}</span>
    </div>
  );
}

function MetricCard({ title, value, change, trend, icon, color }) {
  return (
    <div className="card" style={{ padding: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12,
          background: color + "20", display: "flex",
          alignItems: "center", justifyContent: "center"
        }}>
          <Icon name={icon} size={24} color={color} />
        </div>
        <Icon name={trend === "up" ? "trendingUp" : trend === "down" ? "trendingDown" : "minus"}
              size={16}
              color={trend === "up" ? "var(--green-500)" : trend === "down" ? "var(--red-500)" : "var(--text-muted)"} />
      </div>
      <div style={{ fontSize: 28, fontWeight: 700, marginBottom: 4, color: "var(--text)" }}>
        {value}
      </div>
      <div style={{ fontSize: 12, color: "var(--text-muted)", marginBottom: 8 }}>{title}</div>
      <div style={{
        fontSize: 12,
        color: trend === "up" ? "var(--green-600)" : trend === "down" ? "var(--red-600)" : "var(--text-muted)",
        fontWeight: 500
      }}>
        {change}
      </div>
    </div>
  );
}

// Export the component
window.AdminDashboard = AdminDashboard;